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 warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ['''image_processor''', '''tokenizer'''] lowerCamelCase__ = '''CLIPImageProcessor''' lowerCamelCase__ = ('''XLMRobertaTokenizer''', '''XLMRobertaTokenizerFast''') def __init__( self :Dict , _lowerCamelCase :Optional[int]=None , _lowerCamelCase :Union[str, Any]=None , **_lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop('''feature_extractor''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 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__(_lowerCamelCase , _lowerCamelCase ) def __call__( self :Tuple , _lowerCamelCase :int=None , _lowerCamelCase :Any=None , _lowerCamelCase :Any=None , **_lowerCamelCase :Dict ): 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: __SCREAMING_SNAKE_CASE : List[str] = self.tokenizer(_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) if images is not None: __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor(_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) if text is not None and images is not None: __SCREAMING_SNAKE_CASE : int = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**_lowerCamelCase ) , tensor_type=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , *_lowerCamelCase :Optional[Any] , **_lowerCamelCase :str ): return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , *_lowerCamelCase :int , **_lowerCamelCase :Union[str, Any] ): return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer.model_input_names __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
674
"""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 snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # 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(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) 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 SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = 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. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''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]
674
1
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
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 lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : int , lowercase_ : int , lowercase_ : Dict , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = TapasConfig.from_json_file(lowercase_ ) # set absolute/relative position embeddings parameter __SCREAMING_SNAKE_CASE : Tuple = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": __SCREAMING_SNAKE_CASE : Any = TapasForQuestionAnswering(config=lowercase_ ) elif task == "WTQ": # run_task_main.py hparams __SCREAMING_SNAKE_CASE : Any = 4 __SCREAMING_SNAKE_CASE : Optional[Any] = True # hparam_utils.py hparams __SCREAMING_SNAKE_CASE : Tuple = 0.664_694 __SCREAMING_SNAKE_CASE : List[str] = 0.207_951 __SCREAMING_SNAKE_CASE : Any = 0.121_194 __SCREAMING_SNAKE_CASE : str = True __SCREAMING_SNAKE_CASE : Optional[int] = True __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : str = 0.0_352_513 __SCREAMING_SNAKE_CASE : str = TapasForQuestionAnswering(config=lowercase_ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams __SCREAMING_SNAKE_CASE : Tuple = 4 __SCREAMING_SNAKE_CASE : List[Any] = False # hparam_utils.py hparams __SCREAMING_SNAKE_CASE : List[str] = 36.4_519 __SCREAMING_SNAKE_CASE : Dict = 0.903_421 __SCREAMING_SNAKE_CASE : str = 222.088 __SCREAMING_SNAKE_CASE : Union[str, Any] = True __SCREAMING_SNAKE_CASE : str = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Union[str, Any] = 0.763_141 __SCREAMING_SNAKE_CASE : int = TapasForQuestionAnswering(config=lowercase_ ) elif task == "TABFACT": __SCREAMING_SNAKE_CASE : List[Any] = TapasForSequenceClassification(config=lowercase_ ) elif task == "MLM": __SCREAMING_SNAKE_CASE : List[Any] = TapasForMaskedLM(config=lowercase_ ) elif task == "INTERMEDIATE_PRETRAINING": __SCREAMING_SNAKE_CASE : str = TapasModel(config=lowercase_ ) 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(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model (weights and configuration) print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(lowercase_ ) # Save tokenizer files print(F'''Save tokenizer files to {pytorch_dump_path}''' ) __SCREAMING_SNAKE_CASE : Dict = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowercase_ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": _lowerCamelCase = 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.''' ) _lowerCamelCase = 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, )
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int ): # noqa: E741 '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = 0 __SCREAMING_SNAKE_CASE : List[str] = [0] * n __SCREAMING_SNAKE_CASE : Optional[int] = [False] * n __SCREAMING_SNAKE_CASE : Any = [False] * n def dfs(lowercase_ : Tuple , lowercase_ : Any , lowercase_ : List[Any] , lowercase_ : Dict ): if parent == root: out_edge_count += 1 __SCREAMING_SNAKE_CASE : Optional[int] = True __SCREAMING_SNAKE_CASE : Dict = at for to in l[at]: if to == parent: pass elif not visited[to]: __SCREAMING_SNAKE_CASE : Tuple = dfs(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Any = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: __SCREAMING_SNAKE_CASE : Tuple = True # AP found via cycle if at == low[to]: __SCREAMING_SNAKE_CASE : int = True else: __SCREAMING_SNAKE_CASE : Union[str, Any] = min(low[at] , lowercase_ ) return out_edge_count for i in range(lowercase_ ): if not visited[i]: __SCREAMING_SNAKE_CASE : Dict = 0 __SCREAMING_SNAKE_CASE : Optional[int] = dfs(lowercase_ , lowercase_ , -1 , lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = out_edge_count > 1 for x in range(len(lowercase_ ) ): if is_art[x] is True: print(lowercase_ ) # Adjacency list of graph _lowerCamelCase = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def lowerCAmelCase_ ( ): '''simple docstring''' import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join __SCREAMING_SNAKE_CASE : Any = '''__test_patch_submodule_mock__''' with patch_submodule(_test_patching , '''os.path.join''' , lowercase_ ): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os , _PatchedModuleObj ) assert isinstance(_test_patching.os.path , _PatchedModuleObj ) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path , _PatchedModuleObj ) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os , _PatchedModuleObj ) assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj ) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path , _PatchedModuleObj ) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def lowerCAmelCase_ ( ): '''simple docstring''' assert _test_patching.open is open __SCREAMING_SNAKE_CASE : List[str] = '''__test_patch_submodule_builtin_mock__''' # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching , '''open''' , lowercase_ ): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = '''__test_patch_submodule_missing_mock__''' with patch_submodule(_test_patching , '''pandas.read_csv''' , lowercase_ ): pass def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = '''__test_patch_submodule_missing_builtin_mock__''' # _test_patching doesn't have "len" in its globals assert getattr(_test_patching , '''len''' , lowercase_ ) is None with patch_submodule(_test_patching , '''len''' , lowercase_ ): assert _test_patching.len is mock assert _test_patching.len is len def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = '''__test_patch_submodule_start_and_stop_mock__''' __SCREAMING_SNAKE_CASE : Optional[Any] = patch_submodule(_test_patching , '''open''' , lowercase_ ) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def lowerCAmelCase_ ( ): '''simple docstring''' from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join __SCREAMING_SNAKE_CASE : Optional[Any] = '''__test_patch_submodule_successive_join__''' __SCREAMING_SNAKE_CASE : Any = '''__test_patch_submodule_successive_dirname__''' __SCREAMING_SNAKE_CASE : int = '''__test_patch_submodule_successive_rename__''' assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching , '''os.path.join''' , lowercase_ ): with patch_submodule(_test_patching , '''os.rename''' , lowercase_ ): with patch_submodule(_test_patching , '''os.path.dirname''' , lowercase_ ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching , '''os.rename''' , lowercase_ ): with patch_submodule(_test_patching , '''os.path.join''' , lowercase_ ): with patch_submodule(_test_patching , '''os.path.dirname''' , lowercase_ ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = '''__test_patch_submodule_doesnt_exist_mock__''' with patch_submodule(_test_patching , '''__module_that_doesn_exist__.__attribute_that_doesn_exist__''' , lowercase_ ): pass with patch_submodule(_test_patching , '''os.__attribute_that_doesn_exist__''' , lowercase_ ): pass
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" # # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def lowerCAmelCase_ ( *lowercase_ : Optional[Any] ): '''simple docstring''' with open(lowercase_ , '''r''' ) as fh: fcntl.flock(lowercase_ , fcntl.LOCK_EX ) try: print(*lowercase_ ) finally: fcntl.flock(lowercase_ , fcntl.LOCK_UN ) _lowerCamelCase = int(os.environ['''LOCAL_RANK''']) torch.cuda.set_device(local_rank) _lowerCamelCase = torch.device('''cuda''', local_rank) _lowerCamelCase = socket.gethostname() _lowerCamelCase = f'[{hostname}-{local_rank}]' try: # test distributed dist.init_process_group('''nccl''') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank _lowerCamelCase = dist.get_rank() _lowerCamelCase = dist.get_world_size() printflock(f'{gpu} is OK (global rank: {rank}/{world_size})') dist.barrier() if rank == 0: printflock(f'pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}') except Exception: printflock(f'{gpu} is broken') raise
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal _lowerCamelCase = datasets.utils.logging.get_logger(__name__) _lowerCamelCase = ['''names''', '''prefix'''] _lowerCamelCase = ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols'''] _lowerCamelCase = ['''encoding_errors''', '''on_bad_lines'''] _lowerCamelCase = ['''date_format'''] @dataclass class snake_case ( datasets.BuilderConfig ): lowerCamelCase__ = "," lowerCamelCase__ = None lowerCamelCase__ = "infer" lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = True lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = False lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = True lowerCamelCase__ = True lowerCamelCase__ = False lowerCamelCase__ = True lowerCamelCase__ = None lowerCamelCase__ = "." lowerCamelCase__ = None lowerCamelCase__ = '"' lowerCamelCase__ = 0 lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = True lowerCamelCase__ = True lowerCamelCase__ = 0 lowerCamelCase__ = True lowerCamelCase__ = False lowerCamelCase__ = None lowerCamelCase__ = 10000 lowerCamelCase__ = None lowerCamelCase__ = "strict" lowerCamelCase__ = "error" lowerCamelCase__ = None def SCREAMING_SNAKE_CASE_ ( self :Tuple ): if self.delimiter is not None: __SCREAMING_SNAKE_CASE : int = self.delimiter if self.column_names is not None: __SCREAMING_SNAKE_CASE : Tuple = self.column_names @property def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = { '''sep''': self.sep, '''header''': self.header, '''names''': self.names, '''index_col''': self.index_col, '''usecols''': self.usecols, '''prefix''': self.prefix, '''mangle_dupe_cols''': self.mangle_dupe_cols, '''engine''': self.engine, '''converters''': self.converters, '''true_values''': self.true_values, '''false_values''': self.false_values, '''skipinitialspace''': self.skipinitialspace, '''skiprows''': self.skiprows, '''nrows''': self.nrows, '''na_values''': self.na_values, '''keep_default_na''': self.keep_default_na, '''na_filter''': self.na_filter, '''verbose''': self.verbose, '''skip_blank_lines''': self.skip_blank_lines, '''thousands''': self.thousands, '''decimal''': self.decimal, '''lineterminator''': self.lineterminator, '''quotechar''': self.quotechar, '''quoting''': self.quoting, '''escapechar''': self.escapechar, '''comment''': self.comment, '''encoding''': self.encoding, '''dialect''': self.dialect, '''error_bad_lines''': self.error_bad_lines, '''warn_bad_lines''': self.warn_bad_lines, '''skipfooter''': self.skipfooter, '''doublequote''': self.doublequote, '''memory_map''': self.memory_map, '''float_precision''': self.float_precision, '''chunksize''': self.chunksize, '''encoding_errors''': self.encoding_errors, '''on_bad_lines''': self.on_bad_lines, '''date_format''': self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , _lowerCamelCase ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class snake_case ( datasets.ArrowBasedBuilder ): lowerCamelCase__ = CsvConfig def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return datasets.DatasetInfo(features=self.config.features ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): 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}''' ) __SCREAMING_SNAKE_CASE : List[str] = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCamelCase , (str, list, tuple) ): __SCREAMING_SNAKE_CASE : List[Any] = data_files if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = [files] __SCREAMING_SNAKE_CASE : Dict = [dl_manager.iter_files(_lowerCamelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] __SCREAMING_SNAKE_CASE : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = [files] __SCREAMING_SNAKE_CASE : Dict = [dl_manager.iter_files(_lowerCamelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'''files''': files} ) ) return splits def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :pa.Table ): if self.config.features is not None: __SCREAMING_SNAKE_CASE : str = self.config.features.arrow_schema if all(not require_storage_cast(_lowerCamelCase ) for feature in self.config.features.values() ): # cheaper cast __SCREAMING_SNAKE_CASE : Dict = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=_lowerCamelCase ) else: # more expensive cast; allows str <-> int/float or str to Audio for example __SCREAMING_SNAKE_CASE : List[str] = table_cast(_lowerCamelCase , _lowerCamelCase ) return pa_table def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Tuple = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str __SCREAMING_SNAKE_CASE : Union[str, Any] = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(_lowerCamelCase ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ): __SCREAMING_SNAKE_CASE : Optional[Any] = pd.read_csv(_lowerCamelCase , iterator=_lowerCamelCase , dtype=_lowerCamelCase , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : int = pa.Table.from_pandas(_lowerCamelCase ) # 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 ) except ValueError as e: logger.error(f'''Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}''' ) raise
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''google/pegasus-large''': '''https://huggingface.co/google/pegasus-large/resolve/main/config.json''', # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''pegasus''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__( self :List[Any] , _lowerCamelCase :Optional[int]=5_0_2_6_5 , _lowerCamelCase :Optional[int]=1_0_2_4 , _lowerCamelCase :str=1_2 , _lowerCamelCase :List[Any]=4_0_9_6 , _lowerCamelCase :Optional[Any]=1_6 , _lowerCamelCase :Any=1_2 , _lowerCamelCase :Optional[int]=4_0_9_6 , _lowerCamelCase :List[Any]=1_6 , _lowerCamelCase :Dict=0.0 , _lowerCamelCase :Optional[int]=0.0 , _lowerCamelCase :Any=True , _lowerCamelCase :int=True , _lowerCamelCase :Optional[int]="gelu" , _lowerCamelCase :Union[str, Any]=1_0_2_4 , _lowerCamelCase :int=0.1 , _lowerCamelCase :Dict=0.0 , _lowerCamelCase :Optional[int]=0.0 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[Any]=0 , _lowerCamelCase :Any=False , _lowerCamelCase :Tuple=0 , _lowerCamelCase :int=1 , _lowerCamelCase :Any=1 , **_lowerCamelCase :List[str] , ): __SCREAMING_SNAKE_CASE : str = vocab_size __SCREAMING_SNAKE_CASE : str = max_position_embeddings __SCREAMING_SNAKE_CASE : Optional[int] = d_model __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : int = encoder_layers __SCREAMING_SNAKE_CASE : Any = encoder_attention_heads __SCREAMING_SNAKE_CASE : Optional[Any] = decoder_ffn_dim __SCREAMING_SNAKE_CASE : int = decoder_layers __SCREAMING_SNAKE_CASE : Optional[int] = decoder_attention_heads __SCREAMING_SNAKE_CASE : Any = dropout __SCREAMING_SNAKE_CASE : Optional[Any] = attention_dropout __SCREAMING_SNAKE_CASE : Dict = activation_dropout __SCREAMING_SNAKE_CASE : int = activation_function __SCREAMING_SNAKE_CASE : str = init_std __SCREAMING_SNAKE_CASE : Optional[Any] = encoder_layerdrop __SCREAMING_SNAKE_CASE : Union[str, Any] = decoder_layerdrop __SCREAMING_SNAKE_CASE : Union[str, Any] = use_cache __SCREAMING_SNAKE_CASE : List[str] = encoder_layers __SCREAMING_SNAKE_CASE : str = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , forced_eos_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.d_model
674
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { '''configuration_clap''': [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapAudioConfig''', '''ClapConfig''', '''ClapTextConfig''', ], '''processing_clap''': ['''ClapProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ClapModel''', '''ClapPreTrainedModel''', '''ClapTextModel''', '''ClapTextModelWithProjection''', '''ClapAudioModel''', '''ClapAudioModelWithProjection''', ] _lowerCamelCase = ['''ClapFeatureExtractor'''] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" import os import sys import unittest _lowerCamelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path _lowerCamelCase = os.path.join(git_repo_path, '''src''', '''transformers''') _lowerCamelCase = ''' {0} = None ''' _lowerCamelCase = ''' class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) ''' _lowerCamelCase = ''' def {0}(*args, **kwargs): requires_backends({0}, {1}) ''' class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = find_backend(''' _import_structure["models.albert"].append("AlbertTokenizerFast")''' ) self.assertIsNone(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = find_backend(''' if not is_tokenizers_available():''' ) self.assertEqual(_lowerCamelCase , '''tokenizers''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = find_backend(''' if not is_tensorflow_text_available():''' ) self.assertEqual(_lowerCamelCase , '''tensorflow_text''' ) __SCREAMING_SNAKE_CASE : str = find_backend(''' if not (is_sentencepiece_available() and is_tokenizers_available()):''' ) self.assertEqual(_lowerCamelCase , '''sentencepiece_and_tokenizers''' ) __SCREAMING_SNAKE_CASE : List[str] = find_backend( ''' if not (is_sentencepiece_available() and is_tensorflow_text_available()):''' ) self.assertEqual(_lowerCamelCase , '''sentencepiece_and_tensorflow_text''' ) __SCREAMING_SNAKE_CASE : str = find_backend( ''' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):''' ) self.assertEqual(_lowerCamelCase , '''sentencepiece_and_tokenizers_and_vision''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , _lowerCamelCase ) self.assertIn('''tensorflow_text''' , _lowerCamelCase ) self.assertIn('''sentencepiece_and_tokenizers''' , _lowerCamelCase ) # Likewise, we can't assert on the exact content of a key self.assertIn('''BertModel''' , objects['''torch'''] ) self.assertIn('''TFBertModel''' , objects['''tf'''] ) self.assertIn('''FlaxBertModel''' , objects['''flax'''] ) self.assertIn('''BertModel''' , objects['''torch'''] ) self.assertIn('''TFBertTokenizer''' , objects['''tensorflow_text'''] ) self.assertIn('''convert_slow_tokenizer''' , objects['''sentencepiece_and_tokenizers'''] ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Any = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(_lowerCamelCase , '''\nCONSTANT = None\n''' ) __SCREAMING_SNAKE_CASE : str = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( _lowerCamelCase , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) __SCREAMING_SNAKE_CASE : List[str] = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') ''' __SCREAMING_SNAKE_CASE : Tuple = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) ''' __SCREAMING_SNAKE_CASE : str = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , _lowerCamelCase )
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = set() # edges = list of graph's edges __SCREAMING_SNAKE_CASE : List[str] = 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: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = 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 lowerCAmelCase_ ( lowercase_ : dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = 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)}")
674
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = GPTSanJapaneseTokenizer lowerCamelCase__ = False lowerCamelCase__ = {'''do_clean_text''': False, '''add_prefix_space''': False} def SCREAMING_SNAKE_CASE_ ( self :Any ): super().setUp() # fmt: off __SCREAMING_SNAKE_CASE : Tuple = ['''こん''', '''こんに''', '''にちは''', '''ばんは''', '''世界,㔺界''', '''、''', '''。''', '''<BR>''', '''<SP>''', '''<TAB>''', '''<URL>''', '''<EMAIL>''', '''<TEL>''', '''<DATE>''', '''<PRICE>''', '''<BLOCK>''', '''<KIGOU>''', '''<U2000U2BFF>''', '''<|emoji1|>''', '''<unk>''', '''<|bagoftoken|>''', '''<|endoftext|>'''] # fmt: on __SCREAMING_SNAKE_CASE : str = {'''emoji''': {'''\ud83d\ude00''': '''<|emoji1|>'''}, '''emoji_inv''': {'''<|emoji1|>''': '''\ud83d\ude00'''}} # 😀 __SCREAMING_SNAKE_CASE : Optional[Any] = {'''unk_token''': '''<unk>'''} __SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''emoji_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) with open(self.emoji_file , '''w''' ) as emoji_writer: emoji_writer.write(json.dumps(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , **_lowerCamelCase :Optional[int] ): kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : Dict = '''こんにちは、世界。 \nこんばんは、㔺界。😀''' __SCREAMING_SNAKE_CASE : List[str] = '''こんにちは、世界。 \nこんばんは、世界。😀''' return input_text, output_text def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = self.get_input_output_texts(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.decode(_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase ) return text, ids def SCREAMING_SNAKE_CASE_ ( self :int ): pass # TODO add if relevant def SCREAMING_SNAKE_CASE_ ( self :str ): pass # TODO add if relevant def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): pass # TODO add if relevant def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() # Testing tokenization __SCREAMING_SNAKE_CASE : int = '''こんにちは、世界。 こんばんは、㔺界。''' __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''こん''', '''にちは''', '''、''', '''世界''', '''。''', '''<SP>''', '''こん''', '''ばんは''', '''、''', '''㔺界''', '''。'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) # Testing conversion to ids without special tokens __SCREAMING_SNAKE_CASE : List[Any] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] __SCREAMING_SNAKE_CASE : Tuple = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) # Testing conversion to ids with special tokens __SCREAMING_SNAKE_CASE : Dict = tokens + [tokenizer.unk_token] __SCREAMING_SNAKE_CASE : List[Any] = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 1_9] __SCREAMING_SNAKE_CASE : Any = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizer() # Testing tokenization __SCREAMING_SNAKE_CASE : Any = '''こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。''' __SCREAMING_SNAKE_CASE : str = '''こんにちは、、、、世界。こんばんは、、、、世界。''' __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.encode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.decode(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization __SCREAMING_SNAKE_CASE : Optional[Any] = '''こんにちは、世界。''' __SCREAMING_SNAKE_CASE : Optional[int] = '''こんばんは、㔺界。😀''' __SCREAMING_SNAKE_CASE : Optional[int] = '''こんにちは、世界。こんばんは、世界。😀''' __SCREAMING_SNAKE_CASE : int = tokenizer.encode(prefix_text + input_text ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.encode('''''' , prefix_text=prefix_text + input_text ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.encode(_lowerCamelCase , prefix_text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer.decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.decode(_lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) # Testing tokenization __SCREAMING_SNAKE_CASE : Union[str, Any] = '''こんにちは、世界。''' __SCREAMING_SNAKE_CASE : Optional[Any] = '''こんばんは、㔺界。😀''' __SCREAMING_SNAKE_CASE : Union[str, Any] = len(tokenizer.encode(_lowerCamelCase ) ) - 2 __SCREAMING_SNAKE_CASE : int = len(tokenizer.encode(_lowerCamelCase ) ) - 2 __SCREAMING_SNAKE_CASE : Dict = [1] + [0] * (len_prefix + len_text + 1) __SCREAMING_SNAKE_CASE : Tuple = [1] * (len_prefix + len_text + 1) + [0] __SCREAMING_SNAKE_CASE : Any = [1] + [1] * (len_prefix) + [0] * (len_text + 1) __SCREAMING_SNAKE_CASE : Tuple = tokenizer(prefix_text + input_text ).token_type_ids __SCREAMING_SNAKE_CASE : str = tokenizer('''''' , prefix_text=prefix_text + input_text ).token_type_ids __SCREAMING_SNAKE_CASE : Dict = tokenizer(_lowerCamelCase , prefix_text=_lowerCamelCase ).token_type_ids self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Tuple = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) __SCREAMING_SNAKE_CASE : str = tokenizer.encode('''あンいワ''' ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode('''''' , prefix_text='''あンいワ''' ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode('''いワ''' , prefix_text='''あン''' ) self.assertEqual(tokenizer.decode(_lowerCamelCase ) , tokenizer.decode(_lowerCamelCase ) ) self.assertEqual(tokenizer.decode(_lowerCamelCase ) , tokenizer.decode(_lowerCamelCase ) ) self.assertNotEqual(_lowerCamelCase , _lowerCamelCase ) self.assertNotEqual(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer_class.from_pretrained('''Tanrei/GPTSAN-japanese''' ) __SCREAMING_SNAKE_CASE : Optional[int] = [['''武田信玄''', '''は、'''], ['''織田信長''', '''の配下の、''']] __SCREAMING_SNAKE_CASE : str = tokenizer(_lowerCamelCase , padding=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.batch_encode_plus(_lowerCamelCase , padding=_lowerCamelCase ) # fmt: off __SCREAMING_SNAKE_CASE : Union[str, Any] = [[3_5_9_9_3, 8_6_4_0, 2_5_9_4_8, 3_5_9_9_8, 3_0_6_4_7, 3_5_6_7_5, 3_5_9_9_9, 3_5_9_9_9], [3_5_9_9_3, 1_0_3_8_2, 9_8_6_8, 3_5_9_9_8, 3_0_6_4_6, 9_4_5_9, 3_0_6_4_6, 3_5_6_7_5]] __SCREAMING_SNAKE_CASE : int = [[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] __SCREAMING_SNAKE_CASE : str = [[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , _lowerCamelCase ) self.assertListEqual(x_token.token_type_ids , _lowerCamelCase ) self.assertListEqual(x_token.attention_mask , _lowerCamelCase ) self.assertListEqual(x_token_a.input_ids , _lowerCamelCase ) self.assertListEqual(x_token_a.token_type_ids , _lowerCamelCase ) self.assertListEqual(x_token_a.attention_mask , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def SCREAMING_SNAKE_CASE_ ( self :str ): # tokenizer has no padding token pass
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class snake_case : def __init__( self :List[Any] , _lowerCamelCase :List[Any] , _lowerCamelCase :str=1_3 , _lowerCamelCase :Optional[int]=7 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :Tuple=True , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Union[str, Any]=9_9 , _lowerCamelCase :Tuple=3_2 , _lowerCamelCase :str=2 , _lowerCamelCase :Any=4 , _lowerCamelCase :Dict=3_7 , _lowerCamelCase :Optional[Any]="gelu" , _lowerCamelCase :Tuple=0.1 , _lowerCamelCase :Any=0.1 , _lowerCamelCase :Any=5_1_2 , _lowerCamelCase :str=1_6 , _lowerCamelCase :Optional[Any]=2 , _lowerCamelCase :Dict=0.0_2 , _lowerCamelCase :Tuple=3 , _lowerCamelCase :Any=4 , _lowerCamelCase :int=None , ): __SCREAMING_SNAKE_CASE : Optional[int] = parent __SCREAMING_SNAKE_CASE : Any = 1_3 __SCREAMING_SNAKE_CASE : List[str] = 7 __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : Dict = True __SCREAMING_SNAKE_CASE : Optional[Any] = True __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : List[Any] = 9_9 __SCREAMING_SNAKE_CASE : Dict = 3_2 __SCREAMING_SNAKE_CASE : List[Any] = 2 __SCREAMING_SNAKE_CASE : List[str] = 4 __SCREAMING_SNAKE_CASE : Optional[int] = 3_7 __SCREAMING_SNAKE_CASE : List[Any] = '''gelu''' __SCREAMING_SNAKE_CASE : Union[str, Any] = 0.1 __SCREAMING_SNAKE_CASE : Dict = 0.1 __SCREAMING_SNAKE_CASE : List[Any] = 5_1_2 __SCREAMING_SNAKE_CASE : List[str] = 1_6 __SCREAMING_SNAKE_CASE : Dict = 2 __SCREAMING_SNAKE_CASE : Dict = 0.0_2 __SCREAMING_SNAKE_CASE : Optional[int] = 3 __SCREAMING_SNAKE_CASE : Dict = 4 __SCREAMING_SNAKE_CASE : str = None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_input_mask: __SCREAMING_SNAKE_CASE : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : str = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE : Any = None __SCREAMING_SNAKE_CASE : int = None __SCREAMING_SNAKE_CASE : List[str] = None if self.use_labels: __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE : Tuple = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=_lowerCamelCase , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Any , _lowerCamelCase :List[str] , _lowerCamelCase :List[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : List[str] = TFRoFormerModel(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} __SCREAMING_SNAKE_CASE : Tuple = [input_ids, input_mask] __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Dict , _lowerCamelCase :int , _lowerCamelCase :Tuple , _lowerCamelCase :List[str] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = TFRoFormerForCausalLM(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __SCREAMING_SNAKE_CASE : List[Any] = model(_lowerCamelCase )['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Any , _lowerCamelCase :Optional[int] , _lowerCamelCase :Tuple , _lowerCamelCase :int , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFRoFormerForMaskedLM(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[int] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int , _lowerCamelCase :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.num_labels __SCREAMING_SNAKE_CASE : Dict = TFRoFormerForSequenceClassification(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Tuple , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = self.num_choices __SCREAMING_SNAKE_CASE : str = TFRoFormerForMultipleChoice(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tf.tile(tf.expand_dims(_lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE : str = tf.tile(tf.expand_dims(_lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE : List[Any] = tf.tile(tf.expand_dims(_lowerCamelCase , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Any , _lowerCamelCase :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Tuple = self.num_labels __SCREAMING_SNAKE_CASE : Any = TFRoFormerForTokenClassification(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Dict , _lowerCamelCase :Optional[int] , _lowerCamelCase :Any , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = TFRoFormerForQuestionAnswering(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) : List[str] = config_and_inputs __SCREAMING_SNAKE_CASE : Optional[int] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) lowerCamelCase__ = ( { '''feature-extraction''': TFRoFormerModel, '''fill-mask''': TFRoFormerForMaskedLM, '''question-answering''': TFRoFormerForQuestionAnswering, '''text-classification''': TFRoFormerForSequenceClassification, '''text-generation''': TFRoFormerForCausalLM, '''token-classification''': TFRoFormerForTokenClassification, '''zero-shot''': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Tuple , _lowerCamelCase :List[Any] , _lowerCamelCase :int , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Any = TFRoFormerModelTester(self ) __SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' ) self.assertIsNotNone(_lowerCamelCase ) @require_tf class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Dict = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) __SCREAMING_SNAKE_CASE : int = tf.constant([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE : str = model(_lowerCamelCase )[0] # TODO Replace vocab size __SCREAMING_SNAKE_CASE : Tuple = 5_0_0_0_0 __SCREAMING_SNAKE_CASE : Optional[int] = [1, 6, vocab_size] self.assertEqual(output.shape , _lowerCamelCase ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. __SCREAMING_SNAKE_CASE : Optional[int] = tf.constant( [ [ [-0.1_2_0_5_3_3_4_1, -1.0_2_6_4_9_0_1, 0.2_9_2_2_1_9_4_6], [-1.5_1_3_3_7_8_3, 0.1_9_7_4_3_3, 0.1_5_1_9_0_6_0_7], [-5.0_1_3_5_4_0_3, -3.9_0_0_2_5_6, -0.8_4_0_3_8_7_6_4], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , _lowerCamelCase , atol=1e-4 ) @require_tf class snake_case ( unittest.TestCase ): lowerCamelCase__ = 1e-4 def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Dict = tf.constant([[4, 1_0]] ) __SCREAMING_SNAKE_CASE : List[str] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) __SCREAMING_SNAKE_CASE : Optional[int] = emba(input_ids.shape ) __SCREAMING_SNAKE_CASE : Optional[Any] = tf.constant( [[0.0_0_0_0, 0.0_0_0_0, 0.0_0_0_0, 1.0_0_0_0, 1.0_0_0_0, 1.0_0_0_0], [0.8_4_1_5, 0.0_4_6_4, 0.0_0_2_2, 0.5_4_0_3, 0.9_9_8_9, 1.0_0_0_0]] ) tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , atol=self.tolerance ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Any = tf.constant( [ [0.0_0_0_0, 0.0_0_0_0, 0.0_0_0_0, 0.0_0_0_0, 0.0_0_0_0], [0.8_4_1_5, 0.8_2_1_9, 0.8_0_2_0, 0.7_8_1_9, 0.7_6_1_7], [0.9_0_9_3, 0.9_3_6_4, 0.9_5_8_1, 0.9_7_4_9, 0.9_8_7_0], ] ) __SCREAMING_SNAKE_CASE : Tuple = TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_1_2 , embedding_dim=5_1_2 ) emba([2, 1_6, 5_1_2] ) __SCREAMING_SNAKE_CASE : List[Any] = emba.weight[:3, :5] tf.debugging.assert_near(_lowerCamelCase , _lowerCamelCase , atol=self.tolerance ) @require_tf class snake_case ( unittest.TestCase ): lowerCamelCase__ = 1e-4 def SCREAMING_SNAKE_CASE_ ( self :Any ): # 2,12,16,64 __SCREAMING_SNAKE_CASE : str = tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 __SCREAMING_SNAKE_CASE : List[Any] = -tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 __SCREAMING_SNAKE_CASE : int = TFRoFormerSinusoidalPositionalEmbedding(num_positions=3_2 , embedding_dim=6_4 ) __SCREAMING_SNAKE_CASE : Tuple = embed_positions([2, 1_6, 7_6_8] )[None, None, :, :] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = TFRoFormerSelfAttention.apply_rotary_position_embeddings( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tf.constant( [ [0.0_0_0_0, 0.0_1_0_0, 0.0_2_0_0, 0.0_3_0_0, 0.0_4_0_0, 0.0_5_0_0, 0.0_6_0_0, 0.0_7_0_0], [-0.2_0_1_2, 0.8_8_9_7, 0.0_2_6_3, 0.9_4_0_1, 0.2_0_7_4, 0.9_4_6_3, 0.3_4_8_1, 0.9_3_4_3], [-1.7_0_5_7, 0.6_2_7_1, -1.2_1_4_5, 1.3_8_9_7, -0.6_3_0_3, 1.7_6_4_7, -0.1_1_7_3, 1.8_9_8_5], [-2.1_7_3_1, -1.6_3_9_7, -2.7_3_5_8, 0.2_8_5_4, -2.1_8_4_0, 1.7_1_8_3, -1.3_0_1_8, 2.4_8_7_1], [0.2_7_1_7, -3.6_1_7_3, -2.9_2_0_6, -2.1_9_8_8, -3.6_6_3_8, 0.3_8_5_8, -2.9_1_5_5, 2.2_9_8_0], [3.9_8_5_9, -2.1_5_8_0, -0.7_9_8_4, -4.4_9_0_4, -4.1_1_8_1, -2.0_2_5_2, -4.4_7_8_2, 1.1_2_5_3], ] ) __SCREAMING_SNAKE_CASE : Optional[int] = tf.constant( [ [0.0_0_0_0, -0.0_1_0_0, -0.0_2_0_0, -0.0_3_0_0, -0.0_4_0_0, -0.0_5_0_0, -0.0_6_0_0, -0.0_7_0_0], [0.2_0_1_2, -0.8_8_9_7, -0.0_2_6_3, -0.9_4_0_1, -0.2_0_7_4, -0.9_4_6_3, -0.3_4_8_1, -0.9_3_4_3], [1.7_0_5_7, -0.6_2_7_1, 1.2_1_4_5, -1.3_8_9_7, 0.6_3_0_3, -1.7_6_4_7, 0.1_1_7_3, -1.8_9_8_5], [2.1_7_3_1, 1.6_3_9_7, 2.7_3_5_8, -0.2_8_5_4, 2.1_8_4_0, -1.7_1_8_3, 1.3_0_1_8, -2.4_8_7_1], [-0.2_7_1_7, 3.6_1_7_3, 2.9_2_0_6, 2.1_9_8_8, 3.6_6_3_8, -0.3_8_5_8, 2.9_1_5_5, -2.2_9_8_0], [-3.9_8_5_9, 2.1_5_8_0, 0.7_9_8_4, 4.4_9_0_4, 4.1_1_8_1, 2.0_2_5_2, 4.4_7_8_2, -1.1_2_5_3], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , _lowerCamelCase , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , _lowerCamelCase , atol=self.tolerance )
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : list[list[int | float]] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = len(matrix[0] ) __SCREAMING_SNAKE_CASE : str = min(lowercase_ , lowercase_ ) for row in range(lowercase_ ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , lowercase_ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = matrix[col][row] / matrix[row][row] for i in range(lowercase_ , lowercase_ ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows __SCREAMING_SNAKE_CASE : List[str] = True for i in range(row + 1 , lowercase_ ): if matrix[i][row] != 0: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = matrix[i], matrix[row] __SCREAMING_SNAKE_CASE : Dict = False break if reduce: rank -= 1 for i in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } _lowerCamelCase = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[Any] , lowercase_ : int , lowercase_ : Dict ): '''simple docstring''' for attribute in key.split('''.''' ): __SCREAMING_SNAKE_CASE : Tuple = getattr(lowercase_ , lowercase_ ) if weight_type is not None: __SCREAMING_SNAKE_CASE : Optional[Any] = getattr(lowercase_ , lowercase_ ).shape else: __SCREAMING_SNAKE_CASE : Optional[Any] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": __SCREAMING_SNAKE_CASE : Union[str, Any] = value elif weight_type == "weight_g": __SCREAMING_SNAKE_CASE : Optional[Any] = value elif weight_type == "weight_v": __SCREAMING_SNAKE_CASE : Union[str, Any] = value elif weight_type == "bias": __SCREAMING_SNAKE_CASE : Union[str, Any] = value elif weight_type == "running_mean": __SCREAMING_SNAKE_CASE : str = value elif weight_type == "running_var": __SCREAMING_SNAKE_CASE : Union[str, Any] = value elif weight_type == "num_batches_tracked": __SCREAMING_SNAKE_CASE : int = value elif weight_type == "inv_freq": __SCREAMING_SNAKE_CASE : Optional[Any] = value else: __SCREAMING_SNAKE_CASE : List[Any] = value logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : str , lowercase_ : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [] __SCREAMING_SNAKE_CASE : Dict = fairseq_model.state_dict() __SCREAMING_SNAKE_CASE : Any = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __SCREAMING_SNAKE_CASE : List[Any] = False if "conv_layers" in name: load_conv_layer( lowercase_ , lowercase_ , lowercase_ , lowercase_ , hf_model.config.feat_extract_norm == '''group''' , ) __SCREAMING_SNAKE_CASE : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): __SCREAMING_SNAKE_CASE : Optional[Any] = '''wav2vec2_conformer.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: __SCREAMING_SNAKE_CASE : Optional[int] = True if "*" in mapped_key: __SCREAMING_SNAKE_CASE : List[str] = name.split(lowercase_ )[0].split('''.''' )[-2] __SCREAMING_SNAKE_CASE : Dict = mapped_key.replace('''*''' , lowercase_ ) if "pos_bias_u" in name: __SCREAMING_SNAKE_CASE : List[str] = None elif "pos_bias_v" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = None elif "weight_g" in name: __SCREAMING_SNAKE_CASE : Any = '''weight_g''' elif "weight_v" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = '''weight_v''' elif "bias" in name: __SCREAMING_SNAKE_CASE : Optional[int] = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __SCREAMING_SNAKE_CASE : List[Any] = '''weight''' elif "running_mean" in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = '''running_mean''' elif "inv_freq" in name: __SCREAMING_SNAKE_CASE : str = '''inv_freq''' elif "running_var" in name: __SCREAMING_SNAKE_CASE : List[Any] = '''running_var''' elif "num_batches_tracked" in name: __SCREAMING_SNAKE_CASE : List[Any] = '''num_batches_tracked''' else: __SCREAMING_SNAKE_CASE : int = None set_recursively(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) continue if not is_used: unused_weights.append(lowercase_ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = full_name.split('''conv_layers.''' )[-1] __SCREAMING_SNAKE_CASE : Dict = name.split('''.''' ) __SCREAMING_SNAKE_CASE : Dict = int(items[0] ) __SCREAMING_SNAKE_CASE : List[Any] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : Any = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : Dict = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.''' ) __SCREAMING_SNAKE_CASE : Dict = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowercase_ ) @torch.no_grad() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Union[str, Any] , lowercase_ : List[str]=None , lowercase_ : Any=None , lowercase_ : Tuple=True ): '''simple docstring''' if config_path is not None: __SCREAMING_SNAKE_CASE : Optional[Any] = WavaVecaConformerConfig.from_pretrained(lowercase_ , hidden_act='''swish''' ) else: __SCREAMING_SNAKE_CASE : Optional[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __SCREAMING_SNAKE_CASE : List[str] = '''rotary''' if is_finetuned: if dict_path: __SCREAMING_SNAKE_CASE : Any = Dictionary.load(lowercase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __SCREAMING_SNAKE_CASE : Optional[Any] = target_dict.pad_index __SCREAMING_SNAKE_CASE : Optional[Any] = target_dict.bos_index __SCREAMING_SNAKE_CASE : List[str] = target_dict.eos_index __SCREAMING_SNAKE_CASE : int = len(target_dict.symbols ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(lowercase_ , '''vocab.json''' ) if not os.path.isdir(lowercase_ ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(lowercase_ ) ) return os.makedirs(lowercase_ , exist_ok=lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = target_dict.indices # fairseq has the <pad> and <s> switched __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : Dict = 1 with open(lowercase_ , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = WavaVecaCTCTokenizer( lowercase_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='''|''' , do_lower_case=lowercase_ , ) __SCREAMING_SNAKE_CASE : Any = True if config.feat_extract_norm == '''layer''' else False __SCREAMING_SNAKE_CASE : Optional[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=lowercase_ , return_attention_mask=lowercase_ , ) __SCREAMING_SNAKE_CASE : List[Any] = WavaVecaProcessor(feature_extractor=lowercase_ , tokenizer=lowercase_ ) processor.save_pretrained(lowercase_ ) __SCREAMING_SNAKE_CASE : Any = WavaVecaConformerForCTC(lowercase_ ) else: __SCREAMING_SNAKE_CASE : List[Any] = WavaVecaConformerForPreTraining(lowercase_ ) if is_finetuned: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: __SCREAMING_SNAKE_CASE : Optional[Any] = argparse.Namespace(task='''audio_pretraining''' ) __SCREAMING_SNAKE_CASE : List[Any] = fairseq.tasks.setup_task(lowercase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = model[0].eval() recursively_load_weights(lowercase_ , lowercase_ , not is_finetuned ) hf_wavavec.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) _lowerCamelCase = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" from binascii import hexlify from hashlib import shaaaa from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 _lowerCamelCase = { # 1536-bit 5: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF''', base=16, ), '''generator''': 2, }, # 2048-bit 14: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B''' + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9''' + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510''' + '''15728E5A8AACAA68FFFFFFFFFFFFFFFF''', base=16, ), '''generator''': 2, }, # 3072-bit 15: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B''' + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9''' + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510''' + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64''' + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7''' + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B''' + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C''' + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31''' + '''43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF''', base=16, ), '''generator''': 2, }, # 4096-bit 16: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B''' + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9''' + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510''' + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64''' + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7''' + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B''' + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C''' + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31''' + '''43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7''' + '''88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA''' + '''2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6''' + '''287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED''' + '''1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9''' + '''93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199''' + '''FFFFFFFFFFFFFFFF''', base=16, ), '''generator''': 2, }, # 6144-bit 17: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08''' + '''8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B''' + '''302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9''' + '''A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6''' + '''49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8''' + '''FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C''' + '''180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718''' + '''3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D''' + '''04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D''' + '''B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226''' + '''1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C''' + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC''' + '''E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26''' + '''99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB''' + '''04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2''' + '''233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127''' + '''D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492''' + '''36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406''' + '''AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918''' + '''DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151''' + '''2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03''' + '''F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F''' + '''BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA''' + '''CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B''' + '''B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632''' + '''387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E''' + '''6DCC4024FFFFFFFFFFFFFFFF''', base=16, ), '''generator''': 2, }, # 8192-bit 18: { '''prime''': int( '''FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1''' + '''29024E088A67CC74020BBEA63B139B22514A08798E3404DD''' + '''EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245''' + '''E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED''' + '''EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D''' + '''C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F''' + '''83655D23DCA3AD961C62F356208552BB9ED529077096966D''' + '''670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B''' + '''E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9''' + '''DE2BCBF6955817183995497CEA956AE515D2261898FA0510''' + '''15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64''' + '''ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7''' + '''ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B''' + '''F12FFA06D98A0864D87602733EC86A64521F2B18177B200C''' + '''BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31''' + '''43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7''' + '''88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA''' + '''2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6''' + '''287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED''' + '''1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9''' + '''93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492''' + '''36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD''' + '''F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831''' + '''179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B''' + '''DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF''' + '''5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6''' + '''D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3''' + '''23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA''' + '''CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328''' + '''06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C''' + '''DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE''' + '''12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4''' + '''38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300''' + '''741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568''' + '''3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9''' + '''22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B''' + '''4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A''' + '''062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36''' + '''4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1''' + '''B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92''' + '''4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47''' + '''9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71''' + '''60C980DD98EDD3DFFFFFFFFFFFFFFFFF''', base=16, ), '''generator''': 2, }, } class snake_case : def __init__( self :List[Any] , _lowerCamelCase :int = 1_4 ): if group not in primes: raise ValueError('''Unsupported Group''' ) __SCREAMING_SNAKE_CASE : Optional[int] = primes[group]['''prime'''] __SCREAMING_SNAKE_CASE : str = primes[group]['''generator'''] __SCREAMING_SNAKE_CASE : Tuple = int(hexlify(urandom(3_2 ) ) , base=1_6 ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return hex(self.__private_key )[2:] def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : str = pow(self.generator , self.__private_key , self.prime ) return hex(_lowerCamelCase )[2:] def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :int ): # check if the other public key is valid based on NIST SP800-56 return ( 2 <= key <= self.prime - 2 and pow(_lowerCamelCase , (self.prime - 1) // 2 , self.prime ) == 1 ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Union[str, Any] = int(_lowerCamelCase , base=1_6 ) if not self.is_valid_public_key(_lowerCamelCase ): raise ValueError('''Invalid public key''' ) __SCREAMING_SNAKE_CASE : List[Any] = pow(_lowerCamelCase , self.__private_key , self.prime ) return shaaaa(str(_lowerCamelCase ).encode() ).hexdigest() @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :int , _lowerCamelCase :int ): # check if the other public key is valid based on NIST SP800-56 return ( 2 <= remote_public_key_str <= prime - 2 and pow(_lowerCamelCase , (prime - 1) // 2 , _lowerCamelCase ) == 1 ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :str , _lowerCamelCase :int = 1_4 ): __SCREAMING_SNAKE_CASE : int = int(_lowerCamelCase , base=1_6 ) __SCREAMING_SNAKE_CASE : int = int(_lowerCamelCase , base=1_6 ) __SCREAMING_SNAKE_CASE : str = primes[group]['''prime'''] if not DiffieHellman.is_valid_public_key_static(_lowerCamelCase , _lowerCamelCase ): raise ValueError('''Invalid public key''' ) __SCREAMING_SNAKE_CASE : Any = pow(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return shaaaa(str(_lowerCamelCase ).encode() ).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" from ....utils import logging _lowerCamelCase = logging.get_logger(__name__) class snake_case ( __UpperCAmelCase ): def __init__( self :str , _lowerCamelCase :Any , _lowerCamelCase :Tuple=None , _lowerCamelCase :Optional[int]=2_0_4_8 ): __SCREAMING_SNAKE_CASE : Union[str, Any] = config.__dict__ __SCREAMING_SNAKE_CASE : Union[str, Any] = modal_hidden_size if num_labels: __SCREAMING_SNAKE_CASE : int = num_labels
674
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""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_retribert import RetriBertTokenizer _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowerCamelCase = { '''vocab_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''yjernite/retribert-base-uncased''': ( '''https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json''' ), }, } _lowerCamelCase = { '''yjernite/retribert-base-uncased''': 5_12, } _lowerCamelCase = { '''yjernite/retribert-base-uncased''': {'''do_lower_case''': True}, } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = PRETRAINED_INIT_CONFIGURATION lowerCamelCase__ = RetriBertTokenizer lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :Dict , _lowerCamelCase :int=None , _lowerCamelCase :Optional[int]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Tuple="[UNK]" , _lowerCamelCase :List[str]="[SEP]" , _lowerCamelCase :int="[PAD]" , _lowerCamelCase :Optional[Any]="[CLS]" , _lowerCamelCase :Tuple="[MASK]" , _lowerCamelCase :str=True , _lowerCamelCase :str=None , **_lowerCamelCase :str , ): super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): __SCREAMING_SNAKE_CASE : Any = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) __SCREAMING_SNAKE_CASE : int = do_lower_case __SCREAMING_SNAKE_CASE : Optional[Any] = strip_accents __SCREAMING_SNAKE_CASE : Tuple = tokenize_chinese_chars __SCREAMING_SNAKE_CASE : Optional[Any] = normalizer_class(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = do_lower_case def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Any , _lowerCamelCase :Optional[int]=None ): __SCREAMING_SNAKE_CASE : int = [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 SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[int] = [self.sep_token_id] __SCREAMING_SNAKE_CASE : 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 SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): __SCREAMING_SNAKE_CASE : Tuple = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
674
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __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 : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""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 lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __SCREAMING_SNAKE_CASE : List[Any] = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) __SCREAMING_SNAKE_CASE : List[Any] = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) __SCREAMING_SNAKE_CASE : Dict = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) __SCREAMING_SNAKE_CASE : List[Any] = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) __SCREAMING_SNAKE_CASE : Any = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) __SCREAMING_SNAKE_CASE : Optional[int] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) __SCREAMING_SNAKE_CASE : Any = key.replace('''image_encoder.module''' , '''flava.image_model''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = key.replace('''text_encoder.module''' , '''flava.text_model''' ) __SCREAMING_SNAKE_CASE : Any = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) __SCREAMING_SNAKE_CASE : Any = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) __SCREAMING_SNAKE_CASE : List[Any] = key.replace('''text_projection''' , '''flava.text_projection''' ) __SCREAMING_SNAKE_CASE : int = key.replace('''image_projection''' , '''flava.image_projection''' ) __SCREAMING_SNAKE_CASE : Optional[int] = value.float() for key, value in codebook_state_dict.items(): __SCREAMING_SNAKE_CASE : Any = value return upgrade @torch.no_grad() def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : int=None ): '''simple docstring''' if config_path is not None: __SCREAMING_SNAKE_CASE : str = FlavaConfig.from_pretrained(lowercase_ ) else: __SCREAMING_SNAKE_CASE : Dict = FlavaConfig() __SCREAMING_SNAKE_CASE : List[str] = FlavaForPreTraining(lowercase_ ).eval() __SCREAMING_SNAKE_CASE : str = convert_dalle_checkpoint(lowercase_ , lowercase_ , save_checkpoint=lowercase_ ) if os.path.exists(lowercase_ ): __SCREAMING_SNAKE_CASE : Dict = torch.load(lowercase_ , map_location='''cpu''' ) else: __SCREAMING_SNAKE_CASE : int = torch.hub.load_state_dict_from_url(lowercase_ , map_location='''cpu''' ) __SCREAMING_SNAKE_CASE : List[Any] = upgrade_state_dict(lowercase_ , lowercase_ ) hf_model.load_state_dict(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = hf_model.state_dict() __SCREAMING_SNAKE_CASE : Dict = count_parameters(lowercase_ ) __SCREAMING_SNAKE_CASE : int = count_parameters(lowercase_ ) + count_parameters(lowercase_ ) assert torch.allclose(lowercase_ , lowercase_ , atol=1E-3 ) hf_model.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase = 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''') _lowerCamelCase = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
674
"""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 _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): 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 SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" _lowerCamelCase = [ '''Audio''', '''Array2D''', '''Array3D''', '''Array4D''', '''Array5D''', '''ClassLabel''', '''Features''', '''Sequence''', '''Value''', '''Image''', '''Translation''', '''TranslationVariableLanguages''', ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Any = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : List[Any] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertTrue(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[str] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', '''unet/diffusion_pytorch_model.bin''', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] self.assertTrue(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[str] = [ '''safety_checker/pytorch_model.bin''', '''safety_checker/model.safetensors''', '''vae/diffusion_pytorch_model.bin''', '''vae/diffusion_pytorch_model.safetensors''', '''text_encoder/pytorch_model.bin''', # Removed: 'text_encoder/model.safetensors', '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] self.assertFalse(is_safetensors_compatible(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] __SCREAMING_SNAKE_CASE : int = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : List[str] = [ '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] __SCREAMING_SNAKE_CASE : List[Any] = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # pass variant but use the non-variant filenames __SCREAMING_SNAKE_CASE : List[str] = [ '''unet/diffusion_pytorch_model.bin''', '''unet/diffusion_pytorch_model.safetensors''', ] __SCREAMING_SNAKE_CASE : Dict = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', '''unet/diffusion_pytorch_model.fp16.bin''', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] __SCREAMING_SNAKE_CASE : int = '''fp16''' self.assertFalse(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[int] = [ '''text_encoder/pytorch_model.fp16.bin''', '''text_encoder/model.fp16.safetensors''', ] __SCREAMING_SNAKE_CASE : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # pass variant but use the non-variant filenames __SCREAMING_SNAKE_CASE : List[Any] = [ '''text_encoder/pytorch_model.bin''', '''text_encoder/model.safetensors''', ] __SCREAMING_SNAKE_CASE : Any = '''fp16''' self.assertTrue(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [ '''safety_checker/pytorch_model.fp16.bin''', '''safety_checker/model.fp16.safetensors''', '''vae/diffusion_pytorch_model.fp16.bin''', '''vae/diffusion_pytorch_model.fp16.safetensors''', '''text_encoder/pytorch_model.fp16.bin''', # 'text_encoder/model.fp16.safetensors', '''unet/diffusion_pytorch_model.fp16.bin''', '''unet/diffusion_pytorch_model.fp16.safetensors''', ] __SCREAMING_SNAKE_CASE : List[Any] = '''fp16''' self.assertFalse(is_safetensors_compatible(_lowerCamelCase , variant=_lowerCamelCase ) )
674
"""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 snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # 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(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) 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 SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = 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. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''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]
674
1
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo _lowerCamelCase = '''\ @misc{wu2016googles, title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } ''' _lowerCamelCase = '''\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the \'GLEU score\'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score\'s range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. ''' _lowerCamelCase = '''\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: \'google_bleu\': google_bleu score Examples: Example 1: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results["google_bleu"], 2)) 0.44 Example 2: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results["google_bleu"], 2)) 0.61 Example 3: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results["google_bleu"], 2)) 0.53 Example 4: >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\', ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\'] >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\', ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\', ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\'] >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\', ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\', ... \'heed\', \'the\', \'cat\', \'commands\'] >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\', ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\', ... \'of\', \'the\', \'cat\'] >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\', ... \'interested\', \'in\', \'world\', \'history\'] >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\', ... \'because\', \'he\', \'read\', \'the\', \'book\'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results["google_bleu"], 2)) 0.4 ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ), } ) , ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[List[List[str]]] , _lowerCamelCase :List[List[str]] , _lowerCamelCase :int = 1 , _lowerCamelCase :int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase , hypotheses=_lowerCamelCase , min_len=_lowerCamelCase , max_len=_lowerCamelCase ) }
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''philschmid/bart-large-cnn-samsum''' lowerCamelCase__ = ( '''This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, ''' '''and returns a summary of the text.''' ) lowerCamelCase__ = '''summarizer''' lowerCamelCase__ = AutoTokenizer lowerCamelCase__ = AutoModelForSeqaSeqLM lowerCamelCase__ = ['''text'''] lowerCamelCase__ = ['''text'''] def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[Any] ): return self.pre_processor(_lowerCamelCase , return_tensors='''pt''' , truncation=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Tuple ): return self.model.generate(**_lowerCamelCase )[0] def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Optional[Any] ): return self.pre_processor.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase , clean_up_tokenization_spaces=_lowerCamelCase )
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __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 : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" from __future__ import annotations from PIL import Image # Define glider example _lowerCamelCase = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example _lowerCamelCase = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def lowerCAmelCase_ ( lowercase_ : list[list[int]] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = [] for i in range(len(lowercase_ ) ): __SCREAMING_SNAKE_CASE : Tuple = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours __SCREAMING_SNAKE_CASE : str = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(lowercase_ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(lowercase_ ) - 1: neighbour_count += cells[i + 1][j] if i < len(lowercase_ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. __SCREAMING_SNAKE_CASE : Optional[Any] = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(lowercase_ ) return next_generation def lowerCAmelCase_ ( lowercase_ : list[list[int]] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = [] for _ in range(lowercase_ ): # Create output image __SCREAMING_SNAKE_CASE : str = Image.new('''RGB''' , (len(cells[0] ), len(lowercase_ )) ) __SCREAMING_SNAKE_CASE : int = img.load() # Save cells to image for x in range(len(lowercase_ ) ): for y in range(len(cells[0] ) ): __SCREAMING_SNAKE_CASE : Dict = 255 - cells[y][x] * 255 __SCREAMING_SNAKE_CASE : Union[str, Any] = (colour, colour, colour) # Save image images.append(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = new_generation(lowercase_ ) return images if __name__ == "__main__": _lowerCamelCase = generate_images(GLIDER, 16) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.bert.modeling_flax_bert import ( FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, ) class snake_case ( unittest.TestCase ): def __init__( self :str , _lowerCamelCase :int , _lowerCamelCase :int=1_3 , _lowerCamelCase :Tuple=7 , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Tuple=True , _lowerCamelCase :Any=True , _lowerCamelCase :int=True , _lowerCamelCase :Any=9_9 , _lowerCamelCase :Dict=3_2 , _lowerCamelCase :Optional[int]=5 , _lowerCamelCase :Tuple=4 , _lowerCamelCase :Optional[int]=3_7 , _lowerCamelCase :List[str]="gelu" , _lowerCamelCase :Optional[int]=0.1 , _lowerCamelCase :Dict=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Optional[int]=1_6 , _lowerCamelCase :Optional[Any]=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :int=4 , ): __SCREAMING_SNAKE_CASE : List[Any] = parent __SCREAMING_SNAKE_CASE : int = batch_size __SCREAMING_SNAKE_CASE : int = seq_length __SCREAMING_SNAKE_CASE : Optional[int] = is_training __SCREAMING_SNAKE_CASE : List[Any] = use_attention_mask __SCREAMING_SNAKE_CASE : List[Any] = use_token_type_ids __SCREAMING_SNAKE_CASE : List[str] = use_labels __SCREAMING_SNAKE_CASE : Optional[Any] = vocab_size __SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_size __SCREAMING_SNAKE_CASE : Any = num_hidden_layers __SCREAMING_SNAKE_CASE : str = num_attention_heads __SCREAMING_SNAKE_CASE : str = intermediate_size __SCREAMING_SNAKE_CASE : List[str] = hidden_act __SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = max_position_embeddings __SCREAMING_SNAKE_CASE : str = type_vocab_size __SCREAMING_SNAKE_CASE : Union[str, Any] = type_sequence_label_size __SCREAMING_SNAKE_CASE : Any = initializer_range __SCREAMING_SNAKE_CASE : int = num_choices def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_attention_mask: __SCREAMING_SNAKE_CASE : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE : Optional[Any] = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = config_and_inputs __SCREAMING_SNAKE_CASE : Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = config_and_inputs __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : Tuple = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, ) @require_flax class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = True lowerCamelCase__ = ( ( FlaxBertModel, FlaxBertForPreTraining, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForQuestionAnswering, FlaxBertForNextSentencePrediction, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBertModelTester(self ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): # Only check this for base model, not necessary for all model classes. # This will also help speed-up tests. __SCREAMING_SNAKE_CASE : int = FlaxBertModel.from_pretrained('''bert-base-cased''' ) __SCREAMING_SNAKE_CASE : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase )
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = XLNetTokenizer lowerCamelCase__ = XLNetTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def SCREAMING_SNAKE_CASE_ ( self :str ): super().setUp() # We have a SentencePiece fixture for testing __SCREAMING_SNAKE_CASE : Dict = XLNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : int = '''<s>''' __SCREAMING_SNAKE_CASE : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<eod>''' ) self.assertEqual(len(_lowerCamelCase ) , 1_0_0_6 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_0 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = XLNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_lowerCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2] ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4] ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = XLNetTokenizer(_lowerCamelCase , do_lower_case=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''''', '''i''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''▁he''', '''ll''', '''o'''] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Union[str, Any] = XLNetTokenizer(_lowerCamelCase , do_lower_case=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : str = XLNetTokenizer.from_pretrained('''xlnet-base-cased''' ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer.encode('''sequence builders''' , add_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): # fmt: off __SCREAMING_SNAKE_CASE : Tuple = {'''input_ids''': [[1_7, 2_1_4_4_2, 2_7_0, 1_7, 1_0, 1_4_6_4_5, 3_1_8, 3_4, 1_7, 4_5_4_6, 3_1_4_5, 7_8_7, 1_3, 7_7_5_2, 2_2_0_1_8, 2_3, 2_1, 1_7, 4_5_4_6, 3_1_4_5, 7_8_7, 1_3, 3_3_5_2, 1_4_4_3_1, 1_3, 5_5_0_0, 1_1, 1_1_7_6, 5_8_0, 1_3, 1_6_8_1_9, 4_7_9_7, 2_3, 1_7, 1_0, 1_7_1_3_5, 6_5_8, 1_9, 4_5_7, 7_9_3_2, 1_3, 1_8_4, 1_9, 3_1_5_4, 1_7_1_3_5, 6_4_6_8, 1_9, 1_4_0_4, 1_2_2_6_9, 1_9, 4_2_2_9, 5_3_5_6, 1_6_2_6_4, 4_6, 1_9, 1_7, 2_0_5_4_5, 1_0_3_9_5, 9, 9, 9, 1_1, 2_8, 6_4_2_1, 9_5_3_1, 2_0_7_2_9, 1_7, 1_0, 3_5_3, 1_7_0_2_2, 1_1, 2_1, 6_4_2_1, 9_5_3_1, 1_6_9_4_9, 1_7, 1_0, 1_1_5_0_9, 7_5_3, 1_1, 3_3, 9_5, 2_4_2_1, 7_3_8_5, 9_5_6, 1_4_4_3_1, 2_6_2_6, 2_5, 8_4_2, 7_3_8_5, 4_8_3_6, 2_1, 1_4_2_9, 2_2_7_2, 9_8_5_5, 3_1_2_0, 1_6_1, 2_4_7_3_8, 1_9, 1_3_2_0_3, 6_5_8, 2_1_8, 7_8_7, 2_1, 4_3_0, 1_8_4_8_2, 8_4_7, 2_6_3_7, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_2_2, 2_2_1_7_8, 2_7, 1_0_6_4, 2_2, 9_5_6, 1_3, 1_1_1_0_1, 1_4_2_9, 5_8_5_4, 2_4_3_1_3, 1_8_9_5_3, 4_0, 4_2_2, 2_4_3_6_6, 6_8, 1_7_5_8, 3_7, 1_0_4_8_3, 1_4_2_5_7, 3_1, 2_0_7, 2_6_3, 2_1, 2_0_3, 3_7_7_3, 2_5, 7_1, 9_7_3_5, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_2, 2_0_4_9, 3_4_4_2, 1_7, 1_3_8_9_4, 3_3_8_0, 2_3, 9_5, 1_8, 1_7_6_3_4, 2_2_8_8, 9, 4, 3]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''xlnet-base-cased''' , revision='''c841166438c31ec7ca9a106dee7bb312b73ae511''' , )
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _lowerCamelCase = '''\ @article{wang2019superglue, title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems}, author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R}, journal={arXiv preprint arXiv:1905.00537}, year={2019} } ''' _lowerCamelCase = '''\ SuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after GLUE with a new set of more difficult language understanding tasks, improved resources, and a new public leaderboard. ''' _lowerCamelCase = ''' Compute SuperGLUE evaluation metric associated to each SuperGLUE dataset. Args: predictions: list of predictions to score. Depending on the SuperGlUE subset: - for \'record\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'prediction_text\': the predicted answer text - for \'multirc\': list of question-answer dictionaries with the following keys: - \'idx\': index of the question-answer pair as specified by the dataset - \'prediction\': the predicted answer label - otherwise: list of predicted labels references: list of reference labels. Depending on the SuperGLUE subset: - for \'record\': list of question-answers dictionaries with the following keys: - \'idx\': index of the question as specified by the dataset - \'answers\': list of possible answers - otherwise: list of reference labels Returns: depending on the SuperGLUE subset: - for \'record\': - \'exact_match\': Exact match between answer and gold answer - \'f1\': F1 score - for \'multirc\': - \'exact_match\': Exact match between answer and gold answer - \'f1_m\': Per-question macro-F1 score - \'f1_a\': Average F1 score over all answers - for \'axb\': \'matthews_correlation\': Matthew Correlation - for \'cb\': - \'accuracy\': Accuracy - \'f1\': F1 score - for all others: - \'accuracy\': Accuracy Examples: >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"] >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\') >>> predictions = [0, 1] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\') >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}] >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\') >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}] >>> references = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0} >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\') >>> references = [0, 1] >>> predictions = [0, 1] >>> results = super_glue_metric.compute(predictions=predictions, references=references) >>> print(results) {\'matthews_correlation\': 1.0} ''' def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : List[Any] ): '''simple docstring''' return float((preds == labels).mean() ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : int , lowercase_ : List[Any]="binary" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = simple_accuracy(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : str = float(fa_score(y_true=lowercase_ , y_pred=lowercase_ , average=lowercase_ ) ) return { "accuracy": acc, "f1": fa, } def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = {} for id_pred, label in zip(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[Any] = F'''{id_pred['idx']['paragraph']}-{id_pred['idx']['question']}''' __SCREAMING_SNAKE_CASE : str = id_pred['''prediction'''] if question_id in question_map: question_map[question_id].append((pred, label) ) else: __SCREAMING_SNAKE_CASE : Dict = [(pred, label)] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = [], [] for question, preds_labels in question_map.items(): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = zip(*lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = fa_score(y_true=lowercase_ , y_pred=lowercase_ , average='''macro''' ) fas.append(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = int(sum(pred == label for pred, label in preds_labels ) == len(lowercase_ ) ) ems.append(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = float(sum(lowercase_ ) / len(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[str] = sum(lowercase_ ) / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = float(fa_score(y_true=lowercase_ , y_pred=[id_pred['''prediction'''] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): def SCREAMING_SNAKE_CASE_ ( self :Dict ): if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if not self.config_name == '''record''' and not self.config_name == '''multirc''' else None , ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "prediction_text": datasets.Value('''string''' ), }, "references": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "answers": datasets.Sequence(datasets.Value('''string''' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('''int64''' ), "paragraph": datasets.Value('''int64''' ), "question": datasets.Value('''int64''' ), }, "prediction": datasets.Value('''int64''' ), }, "references": datasets.Value('''int64''' ), } else: return { "predictions": datasets.Value('''int64''' ), "references": datasets.Value('''int64''' ), } def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[str] , _lowerCamelCase :List[Any] ): if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_lowerCamelCase , _lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(_lowerCamelCase , _lowerCamelCase , fa_avg='''macro''' ) elif self.config_name == "record": __SCREAMING_SNAKE_CASE : Optional[int] = [ { '''qas''': [ {'''id''': ref['''idx''']['''query'''], '''answers''': [{'''text''': ans} for ans in ref['''answers''']]} for ref in references ] } ] __SCREAMING_SNAKE_CASE : Dict = {pred['''idx''']['''query''']: pred['''prediction_text'''] for pred in predictions} return evaluate_record(_lowerCamelCase , _lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(_lowerCamelCase , _lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_lowerCamelCase , _lowerCamelCase )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' )
674
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = 42 lowerCamelCase__ = 42 def __init__( self :Optional[Any] , _lowerCamelCase :UNetaDModel , _lowerCamelCase :ScoreSdeVeScheduler ): super().__init__() self.register_modules(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) @torch.no_grad() def __call__( self :Dict , _lowerCamelCase :int = 1 , _lowerCamelCase :int = 2_0_0_0 , _lowerCamelCase :Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowerCamelCase :Optional[str] = "pil" , _lowerCamelCase :bool = True , **_lowerCamelCase :Dict , ): __SCREAMING_SNAKE_CASE : Dict = self.unet.config.sample_size __SCREAMING_SNAKE_CASE : int = (batch_size, 3, img_size, img_size) __SCREAMING_SNAKE_CASE : Any = self.unet __SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor(_lowerCamelCase , generator=_lowerCamelCase ) * self.scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE : Any = sample.to(self.device ) self.scheduler.set_timesteps(_lowerCamelCase ) self.scheduler.set_sigmas(_lowerCamelCase ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): __SCREAMING_SNAKE_CASE : Dict = self.unet(_lowerCamelCase , _lowerCamelCase ).sample __SCREAMING_SNAKE_CASE : Dict = self.scheduler.step_correct(_lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase ).prev_sample # prediction step __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase , _lowerCamelCase ).sample __SCREAMING_SNAKE_CASE : List[Any] = self.scheduler.step_pred(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , generator=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = output.prev_sample, output.prev_sample_mean __SCREAMING_SNAKE_CASE : str = sample_mean.clamp(0 , 1 ) __SCREAMING_SNAKE_CASE : List[Any] = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE : Optional[Any] = self.numpy_to_pil(_lowerCamelCase ) if not return_dict: return (sample,) return ImagePipelineOutput(images=_lowerCamelCase )
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" from typing import Any import numpy as np def lowerCAmelCase_ ( lowercase_ : np.ndarray ): '''simple docstring''' return np.array_equal(lowercase_ , matrix.conjugate().T ) def lowerCAmelCase_ ( lowercase_ : np.ndarray , lowercase_ : np.ndarray ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = v.conjugate().T __SCREAMING_SNAKE_CASE : int = v_star.dot(lowercase_ ) assert isinstance(lowercase_ , np.ndarray ) return (v_star_dot.dot(lowercase_ )) / (v_star.dot(lowercase_ )) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]] ) __SCREAMING_SNAKE_CASE : Any = np.array([[1], [2], [3]] ) assert is_hermitian(lowercase_ ), F'''{a} is not hermitian.''' print(rayleigh_quotient(lowercase_ , lowercase_ ) ) __SCREAMING_SNAKE_CASE : int = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowercase_ ), F'''{a} is not hermitian.''' assert rayleigh_quotient(lowercase_ , lowercase_ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels _lowerCamelCase = object() # For specifying empty leaf dict `{}` _lowerCamelCase = object() def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : List[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = tuple((re.compile(x + '''$''' ) for x in qs) ) for i in range(len(lowercase_ ) - len(lowercase_ ) + 1 ): __SCREAMING_SNAKE_CASE : Optional[int] = [x.match(lowercase_ ) for x, y in zip(lowercase_ , ks[i:] )] if matches and all(lowercase_ ): return True return False def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' def replace(lowercase_ : Dict , lowercase_ : Optional[Any] ): for rule, replacement in rules: if _match(lowercase_ , lowercase_ ): return replacement return val return replace def lowerCAmelCase_ ( ): '''simple docstring''' return [ # embeddings (("transformer", "wpe", "embedding"), P('''mp''' , lowercase_ )), (("transformer", "wte", "embedding"), P('''mp''' , lowercase_ )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowercase_ , '''mp''' )), (("attention", "out_proj", "kernel"), P('''mp''' , lowercase_ )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(lowercase_ , '''mp''' )), (("mlp", "c_fc", "bias"), P('''mp''' )), (("mlp", "c_proj", "kernel"), P('''mp''' , lowercase_ )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = _get_partition_rules() __SCREAMING_SNAKE_CASE : Tuple = _replacement_rules(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = {k: _unmatched for k in flatten_dict(lowercase_ )} __SCREAMING_SNAKE_CASE : List[Any] = {k: replace(lowercase_ , lowercase_ ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(lowercase_ ) )
674
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" from __future__ import annotations class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Union[str, Any]=None ): __SCREAMING_SNAKE_CASE : int = data __SCREAMING_SNAKE_CASE : Any = None def __repr__( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = [] __SCREAMING_SNAKE_CASE : Optional[Any] = self while temp: string_rep.append(f'''{temp.data}''' ) __SCREAMING_SNAKE_CASE : Tuple = temp.next return "->".join(_lowerCamelCase ) def lowerCAmelCase_ ( lowercase_ : list ): '''simple docstring''' if not elements_list: raise Exception('''The Elements List is empty''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = Node(elements_list[0] ) for i in range(1 , len(lowercase_ ) ): __SCREAMING_SNAKE_CASE : Dict = Node(elements_list[i] ) __SCREAMING_SNAKE_CASE : Any = current.next return head def lowerCAmelCase_ ( lowercase_ : Node ): '''simple docstring''' if head_node is not None and isinstance(lowercase_ , lowercase_ ): print_reverse(head_node.next ) print(head_node.data ) def lowerCAmelCase_ ( ): '''simple docstring''' from doctest import testmod testmod() __SCREAMING_SNAKE_CASE : str = make_linked_list([14, 52, 14, 12, 43] ) print('''Linked List:''' ) print(lowercase_ ) print('''Elements in Reverse:''' ) print_reverse(lowercase_ ) if __name__ == "__main__": main()
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" import os _lowerCamelCase = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 1_00, '''D''': 5_00, '''M''': 10_00} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = 0 __SCREAMING_SNAKE_CASE : Tuple = 0 while index < len(lowercase_ ) - 1: __SCREAMING_SNAKE_CASE : Tuple = SYMBOLS[numerals[index]] __SCREAMING_SNAKE_CASE : str = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = '''''' __SCREAMING_SNAKE_CASE : Any = num // 1000 numerals += m_count * "M" num %= 1000 __SCREAMING_SNAKE_CASE : int = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 __SCREAMING_SNAKE_CASE : Optional[Any] = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def lowerCAmelCase_ ( lowercase_ : str = "/p089_roman.txt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 with open(os.path.dirname(lowercase_ ) + roman_numerals_filename ) as filea: __SCREAMING_SNAKE_CASE : List[str] = filea.readlines() for line in lines: __SCREAMING_SNAKE_CASE : List[Any] = line.strip() __SCREAMING_SNAKE_CASE : Tuple = parse_roman_numerals(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = generate_roman_numerals(lowercase_ ) savings += len(lowercase_ ) - len(lowercase_ ) return savings if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" # Copyright 2022 The HuggingFace Team and The OpenBMB 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_tokenizers_available, is_torch_available _lowerCamelCase = { '''configuration_cpmant''': ['''CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CpmAntConfig'''], '''tokenization_cpmant''': ['''CpmAntTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CpmAntForCausalLM''', '''CpmAntModel''', '''CpmAntPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = TransfoXLTokenizer lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :List[str] ): super().setUp() __SCREAMING_SNAKE_CASE : Optional[Any] = [ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , **_lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Tuple = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : List[str] = '''<unk> UNwanted , running''' __SCREAMING_SNAKE_CASE : str = '''<unk> unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(_lowerCamelCase , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [0, 4, 8, 7] ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : str = TransfoXLTokenizer(lower_case=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = TransfoXLTokenizer(lower_case=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[str] = TransfoXLTokenizer(lower_case=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' __SCREAMING_SNAKE_CASE : List[Any] = [ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = len(_lowerCamelCase ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(_lowerCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" import doctest from collections import deque import numpy as np class snake_case : def __init__( self :Optional[int] ): __SCREAMING_SNAKE_CASE : int = [2, 1, 2, -1] __SCREAMING_SNAKE_CASE : List[str] = [1, 2, 3, 4] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = len(self.first_signal ) __SCREAMING_SNAKE_CASE : Optional[int] = len(self.second_signal ) __SCREAMING_SNAKE_CASE : Any = max(_lowerCamelCase , _lowerCamelCase ) # create a zero matrix of max_length x max_length __SCREAMING_SNAKE_CASE : Optional[int] = [[0] * max_length for i in range(_lowerCamelCase )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = deque(self.second_signal ) rotated_signal.rotate(_lowerCamelCase ) for j, item in enumerate(_lowerCamelCase ): matrix[i][j] += item # multiply the matrix with the first signal __SCREAMING_SNAKE_CASE : str = np.matmul(np.transpose(_lowerCamelCase ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(_lowerCamelCase , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = int(lowercase_ ) if decimal in (0, 1): # Exit cases for the recursion return str(lowercase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = divmod(lowercase_ , 2 ) return binary_recursive(lowercase_ ) + str(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = str(lowercase_ ).strip() if not number: raise ValueError('''No input value was provided''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''-''' if number.startswith('''-''' ) else '''''' __SCREAMING_SNAKE_CASE : str = number.lstrip('''-''' ) if not number.isnumeric(): raise ValueError('''Input value is not an integer''' ) return F'''{negative}0b{binary_recursive(int(lowercase_ ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Dict = '''laion/clap-htsat-unfused''' __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE_ ( self :Tuple , **_lowerCamelCase :List[str] ): return RobertaTokenizer.from_pretrained(self.checkpoint , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :Optional[int] ): return ClapFeatureExtractor.from_pretrained(self.checkpoint , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = self.get_feature_extractor() __SCREAMING_SNAKE_CASE : Union[str, Any] = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Dict = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_feature_extractor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : List[str] = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_feature_extractor() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = floats_list((3, 1_0_0_0) ) __SCREAMING_SNAKE_CASE : int = feature_extractor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : str = processor(audios=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_feature_extractor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Any = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = '''This is a test string''' __SCREAMING_SNAKE_CASE : List[Any] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : int = self.get_feature_extractor() __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : str = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Dict = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : str = self.get_feature_extractor() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , )
674
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __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 : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: _lowerCamelCase = False _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = '''ybelkada/fonts''' def lowerCAmelCase_ ( ): '''simple docstring''' if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F'''You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use ''' '''Pix2StructImageProcessor. Please upgrade torch.''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : List[str] ): '''simple docstring''' requires_backends(lowercase_ , ['''torch'''] ) _check_torch_version() __SCREAMING_SNAKE_CASE : Any = image_tensor.unsqueeze(0 ) __SCREAMING_SNAKE_CASE : Any = torch.nn.functional.unfold(lowercase_ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) __SCREAMING_SNAKE_CASE : List[Any] = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , lowercase_ , lowercase_ , -1 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : int = 36 , lowercase_ : str = "black" , lowercase_ : str = "white" , lowercase_ : int = 5 , lowercase_ : int = 5 , lowercase_ : int = 5 , lowercase_ : int = 5 , lowercase_ : Optional[bytes] = None , lowercase_ : Optional[str] = None , ): '''simple docstring''' requires_backends(lowercase_ , '''vision''' ) # Add new lines so that each line is no more than 80 characters. __SCREAMING_SNAKE_CASE : Tuple = textwrap.TextWrapper(width=80 ) __SCREAMING_SNAKE_CASE : Dict = wrapper.wrap(text=lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = '''\n'''.join(lowercase_ ) if font_bytes is not None and font_path is None: __SCREAMING_SNAKE_CASE : str = io.BytesIO(lowercase_ ) elif font_path is not None: __SCREAMING_SNAKE_CASE : Union[str, Any] = font_path else: __SCREAMING_SNAKE_CASE : Any = hf_hub_download(lowercase_ , '''Arial.TTF''' ) __SCREAMING_SNAKE_CASE : Tuple = ImageFont.truetype(lowercase_ , encoding='''UTF-8''' , size=lowercase_ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. __SCREAMING_SNAKE_CASE : str = ImageDraw.Draw(Image.new('''RGB''' , (1, 1) , lowercase_ ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = temp_draw.textbbox((0, 0) , lowercase_ , lowercase_ ) # Create the actual image with a bit of padding around the text. __SCREAMING_SNAKE_CASE : Optional[Any] = text_width + left_padding + right_padding __SCREAMING_SNAKE_CASE : int = text_height + top_padding + bottom_padding __SCREAMING_SNAKE_CASE : int = Image.new('''RGB''' , (image_width, image_height) , lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = ImageDraw.Draw(lowercase_ ) draw.text(xy=(left_padding, top_padding) , text=lowercase_ , fill=lowercase_ , font=lowercase_ ) return image def lowerCAmelCase_ ( lowercase_ : np.ndarray , lowercase_ : str , **lowercase_ : Optional[int] ): '''simple docstring''' requires_backends(lowercase_ , '''vision''' ) # Convert to PIL image if necessary __SCREAMING_SNAKE_CASE : Optional[Any] = to_pil_image(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = render_text(lowercase_ , **lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = max(header_image.width , image.width ) __SCREAMING_SNAKE_CASE : Any = int(image.height * (new_width / image.width) ) __SCREAMING_SNAKE_CASE : Any = int(header_image.height * (new_width / header_image.width) ) __SCREAMING_SNAKE_CASE : List[Any] = Image.new('''RGB''' , (new_width, new_height + new_header_height) , '''white''' ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary __SCREAMING_SNAKE_CASE : Any = to_numpy_array(lowercase_ ) if infer_channel_dimension_format(lowercase_ ) == ChannelDimension.LAST: __SCREAMING_SNAKE_CASE : str = to_channel_dimension_format(lowercase_ , ChannelDimension.LAST ) return new_image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ['''flattened_patches'''] def __init__( self :Optional[int] , _lowerCamelCase :bool = True , _lowerCamelCase :bool = True , _lowerCamelCase :Dict[str, int] = None , _lowerCamelCase :int = 2_0_4_8 , _lowerCamelCase :bool = False , **_lowerCamelCase :Optional[int] , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = patch_size if patch_size is not None else {'''height''': 1_6, '''width''': 1_6} __SCREAMING_SNAKE_CASE : List[Any] = do_normalize __SCREAMING_SNAKE_CASE : Tuple = do_convert_rgb __SCREAMING_SNAKE_CASE : str = max_patches __SCREAMING_SNAKE_CASE : Any = is_vqa def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :np.ndarray , _lowerCamelCase :int , _lowerCamelCase :dict , **_lowerCamelCase :Optional[Any] ): requires_backends(self.extract_flattened_patches , '''torch''' ) _check_torch_version() # convert to torch __SCREAMING_SNAKE_CASE : Any = to_channel_dimension_format(_lowerCamelCase , ChannelDimension.FIRST ) __SCREAMING_SNAKE_CASE : Dict = torch.from_numpy(_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = patch_size['''height'''], patch_size['''width'''] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = get_image_size(_lowerCamelCase ) # maximize scale s.t. __SCREAMING_SNAKE_CASE : Optional[Any] = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) __SCREAMING_SNAKE_CASE : List[Any] = max(min(math.floor(scale * image_height / patch_height ) , _lowerCamelCase ) , 1 ) __SCREAMING_SNAKE_CASE : str = max(min(math.floor(scale * image_width / patch_width ) , _lowerCamelCase ) , 1 ) __SCREAMING_SNAKE_CASE : Dict = max(num_feasible_rows * patch_height , 1 ) __SCREAMING_SNAKE_CASE : List[str] = max(num_feasible_cols * patch_width , 1 ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.nn.functional.interpolate( image.unsqueeze(0 ) , size=(resized_height, resized_width) , mode='''bilinear''' , align_corners=_lowerCamelCase , antialias=_lowerCamelCase , ).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] __SCREAMING_SNAKE_CASE : Any = torch_extract_patches(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = patches.shape __SCREAMING_SNAKE_CASE : List[Any] = patches_shape[1] __SCREAMING_SNAKE_CASE : str = patches_shape[2] __SCREAMING_SNAKE_CASE : Dict = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] __SCREAMING_SNAKE_CASE : Optional[int] = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.arange(_lowerCamelCase ).reshape([rows, 1] ).repeat(1 , _lowerCamelCase ).reshape([rows * columns, 1] ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.arange(_lowerCamelCase ).reshape([1, columns] ).repeat(_lowerCamelCase , 1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] __SCREAMING_SNAKE_CASE : str = row_ids.to(torch.floataa ) __SCREAMING_SNAKE_CASE : int = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] __SCREAMING_SNAKE_CASE : List[Any] = torch.cat([row_ids, col_ids, patches] , -1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] __SCREAMING_SNAKE_CASE : Optional[int] = torch.nn.functional.pad(_lowerCamelCase , [0, 0, 0, max_patches - (rows * columns)] ).float() __SCREAMING_SNAKE_CASE : int = to_numpy_array(_lowerCamelCase ) return result def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :np.ndarray , _lowerCamelCase :Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase :List[str] ): if image.dtype == np.uinta: __SCREAMING_SNAKE_CASE : List[Any] = image.astype(np.floataa ) # take mean across the whole `image` __SCREAMING_SNAKE_CASE : str = np.mean(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = np.std(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = max(_lowerCamelCase , 1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :ImageInput , _lowerCamelCase :Optional[str] = None , _lowerCamelCase :bool = None , _lowerCamelCase :Optional[bool] = None , _lowerCamelCase :Optional[int] = None , _lowerCamelCase :Optional[Dict[str, int]] = None , _lowerCamelCase :Optional[Union[str, TensorType]] = None , _lowerCamelCase :ChannelDimension = ChannelDimension.FIRST , **_lowerCamelCase :Optional[Any] , ): __SCREAMING_SNAKE_CASE : Dict = do_normalize if do_normalize is not None else self.do_normalize __SCREAMING_SNAKE_CASE : Dict = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __SCREAMING_SNAKE_CASE : Any = patch_size if patch_size is not None else self.patch_size __SCREAMING_SNAKE_CASE : List[str] = max_patches if max_patches is not None else self.max_patches __SCREAMING_SNAKE_CASE : Union[str, Any] = self.is_vqa if kwargs.get('''data_format''' , _lowerCamelCase ) is not None: raise ValueError('''data_format is not an accepted input as the outputs are ''' ) __SCREAMING_SNAKE_CASE : Dict = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __SCREAMING_SNAKE_CASE : Optional[int] = [convert_to_rgb(_lowerCamelCase ) for image in images] # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE : Any = [to_numpy_array(_lowerCamelCase ) for image in images] if is_vqa: if header_text is None: raise ValueError('''A header text must be provided for VQA models.''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs.pop('''font_bytes''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = kwargs.pop('''font_path''' , _lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = [header_text] * len(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = [ render_header(_lowerCamelCase , header_text[i] , font_bytes=_lowerCamelCase , font_path=_lowerCamelCase ) for i, image in enumerate(_lowerCamelCase ) ] if do_normalize: __SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=_lowerCamelCase ) for image in images] # convert to torch tensor and permute __SCREAMING_SNAKE_CASE : Optional[Any] = [ self.extract_flattened_patches(image=_lowerCamelCase , max_patches=_lowerCamelCase , patch_size=_lowerCamelCase ) for image in images ] # create attention mask in numpy __SCREAMING_SNAKE_CASE : Dict = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] __SCREAMING_SNAKE_CASE : int = BatchFeature( data={'''flattened_patches''': images, '''attention_mask''': attention_masks} , tensor_type=_lowerCamelCase ) return encoded_outputs
674
"""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 _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): 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 SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Optional[int]=False ): '''simple docstring''' try: __SCREAMING_SNAKE_CASE : List[Any] = os.environ[key] except KeyError: # KEY isn't set, default to `default`. __SCREAMING_SNAKE_CASE : Dict = default else: # KEY is set, convert it to True or False. try: __SCREAMING_SNAKE_CASE : Any = strtobool(lowercase_ ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F'''If set, {key} must be yes or no.''' ) return _value _lowerCamelCase = parse_flag_from_env('''RUN_SLOW''', default=False) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' return unittest.skip('''Test was skipped''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' return unittest.skipUnless(_run_slow_tests , '''test is slow''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available() , '''test requires only a CPU''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available() , '''test requires a GPU''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' return unittest.skipUnless(is_xpu_available() , '''test requires a XPU''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' return unittest.skipUnless(is_mps_available() , '''test requires a `mps` backend support in `torch`''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available() , '''test requires the Hugging Face suite''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return unittest.skipUnless(is_bnb_available() , '''test requires the bitsandbytes library''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Dict ): '''simple docstring''' return unittest.skipUnless(is_tpu_available() , '''test requires TPU''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1 , '''test requires a GPU''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1 , '''test requires a XPU''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1 , '''test requires multiple GPUs''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1 , '''test requires multiple XPUs''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return unittest.skipUnless(is_safetensors_available() , '''test requires safetensors''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Dict ): '''simple docstring''' return unittest.skipUnless(is_deepspeed_available() , '''test requires DeepSpeed''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' return unittest.skipUnless(is_torch_version('''>=''' , '''1.12.0''' ) , '''test requires torch version >= 1.12.0''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any=None , lowercase_ : int=None ): '''simple docstring''' if test_case is None: return partial(lowercase_ , version=lowercase_ ) return unittest.skipUnless(is_torch_version('''>=''' , lowercase_ ) , F'''test requires torch version >= {version}''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] ): '''simple docstring''' return unittest.skipUnless(is_tensorboard_available() , '''test requires Tensorboard''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return unittest.skipUnless(is_wandb_available() , '''test requires wandb''' )(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] ): '''simple docstring''' return unittest.skipUnless(is_comet_ml_available() , '''test requires comet_ml''' )(lowercase_ ) _lowerCamelCase = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def lowerCAmelCase_ ( lowercase_ : Dict ): '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available , '''test requires at least one tracker to be available and for `comet_ml` to not be installed''' , )(lowercase_ ) class snake_case ( unittest.TestCase ): lowerCamelCase__ = True @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Optional[int] ): __SCREAMING_SNAKE_CASE : Optional[Any] = tempfile.mkdtemp() @classmethod def SCREAMING_SNAKE_CASE_ ( cls :str ): if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): if self.clear_on_setup: for path in Path(self.tmpdir ).glob('''**/*''' ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(_lowerCamelCase ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Union[mock.Mock, List[mock.Mock]] ): __SCREAMING_SNAKE_CASE : Optional[Any] = mocks if isinstance(_lowerCamelCase , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def lowerCAmelCase_ ( lowercase_ : Dict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = AcceleratorState() __SCREAMING_SNAKE_CASE : List[Any] = tensor[None].clone().to(state.device ) __SCREAMING_SNAKE_CASE : List[Any] = gather(lowercase_ ).cpu() __SCREAMING_SNAKE_CASE : str = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , lowercase_ ): return False return True class snake_case : def __init__( self :str , _lowerCamelCase :Any , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : Any = returncode __SCREAMING_SNAKE_CASE : Union[str, Any] = stdout __SCREAMING_SNAKE_CASE : Any = stderr async def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] ): '''simple docstring''' while True: __SCREAMING_SNAKE_CASE : Optional[int] = await stream.readline() if line: callback(lowercase_ ) else: break async def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[Any]=None , lowercase_ : Union[str, Any]=None , lowercase_ : List[str]=None , lowercase_ : List[Any]=False , lowercase_ : Tuple=False ): '''simple docstring''' if echo: print('''\nRunning: ''' , ''' '''.join(lowercase_ ) ) __SCREAMING_SNAKE_CASE : int = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=lowercase_ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=lowercase_ , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Union[str, Any] = [] def tee(lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict , lowercase_ : Optional[int]="" ): __SCREAMING_SNAKE_CASE : List[str] = line.decode('''utf-8''' ).rstrip() sink.append(lowercase_ ) if not quiet: print(lowercase_ , lowercase_ , file=lowercase_ ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda lowercase_ : tee(lowercase_ , lowercase_ , sys.stdout , label='''stdout:''' ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda lowercase_ : tee(lowercase_ , lowercase_ , sys.stderr , label='''stderr:''' ) ) ), ] , timeout=lowercase_ , ) return _RunOutput(await p.wait() , lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : int=None , lowercase_ : Tuple=None , lowercase_ : Optional[Any]=180 , lowercase_ : List[Any]=False , lowercase_ : str=True ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = asyncio.get_event_loop() __SCREAMING_SNAKE_CASE : List[Any] = loop.run_until_complete( _stream_subprocess(lowercase_ , env=lowercase_ , stdin=lowercase_ , timeout=lowercase_ , quiet=lowercase_ , echo=lowercase_ ) ) __SCREAMING_SNAKE_CASE : Tuple = ''' '''.join(lowercase_ ) if result.returncode > 0: __SCREAMING_SNAKE_CASE : int = '''\n'''.join(result.stderr ) raise RuntimeError( F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n''' F'''The combined stderr from workers follows:\n{stderr}''' ) return result class snake_case ( __UpperCAmelCase ): pass def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str=False ): '''simple docstring''' try: __SCREAMING_SNAKE_CASE : Tuple = subprocess.check_output(lowercase_ , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(lowercase_ , '''decode''' ): __SCREAMING_SNAKE_CASE : List[str] = output.decode('''utf-8''' ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F'''Command `{' '.join(lowercase_ )}` failed with the following error:\n\n{e.output.decode()}''' ) from e
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
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 _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): 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 SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[int] , _lowerCamelCase :UNetaDModel , _lowerCamelCase :UNetaDModel , _lowerCamelCase :DDPMScheduler , _lowerCamelCase :Tuple , ): super().__init__() __SCREAMING_SNAKE_CASE : Tuple = value_function __SCREAMING_SNAKE_CASE : List[Any] = unet __SCREAMING_SNAKE_CASE : List[str] = scheduler __SCREAMING_SNAKE_CASE : Optional[Any] = env __SCREAMING_SNAKE_CASE : int = env.get_dataset() __SCREAMING_SNAKE_CASE : Optional[int] = {} for key in self.data.keys(): try: __SCREAMING_SNAKE_CASE : Tuple = self.data[key].mean() except: # noqa: E722 pass __SCREAMING_SNAKE_CASE : str = {} for key in self.data.keys(): try: __SCREAMING_SNAKE_CASE : str = self.data[key].std() except: # noqa: E722 pass __SCREAMING_SNAKE_CASE : Tuple = env.observation_space.shape[0] __SCREAMING_SNAKE_CASE : List[Any] = env.action_space.shape[0] def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[str] , _lowerCamelCase :List[str] ): return (x_in - self.means[key]) / self.stds[key] def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Tuple , _lowerCamelCase :str ): return x_in * self.stds[key] + self.means[key] def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int ): if type(_lowerCamelCase ) is dict: return {k: self.to_torch(_lowerCamelCase ) for k, v in x_in.items()} elif torch.is_tensor(_lowerCamelCase ): return x_in.to(self.unet.device ) return torch.tensor(_lowerCamelCase , device=self.unet.device ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :int , _lowerCamelCase :Optional[Any] ): for key, val in cond.items(): __SCREAMING_SNAKE_CASE : int = val.clone() return x_in def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[Any] , _lowerCamelCase :Any , _lowerCamelCase :int , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Any = x.shape[0] __SCREAMING_SNAKE_CASE : int = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model __SCREAMING_SNAKE_CASE : Optional[int] = torch.full((batch_size,) , _lowerCamelCase , device=self.unet.device , dtype=torch.long ) for _ in range(_lowerCamelCase ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models __SCREAMING_SNAKE_CASE : str = self.value_function(x.permute(0 , 2 , 1 ) , _lowerCamelCase ).sample __SCREAMING_SNAKE_CASE : Dict = torch.autograd.grad([y.sum()] , [x] )[0] __SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler._get_variance(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = torch.exp(0.5 * posterior_variance ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model_std * grad __SCREAMING_SNAKE_CASE : int = 0 __SCREAMING_SNAKE_CASE : Union[str, Any] = x.detach() __SCREAMING_SNAKE_CASE : Optional[Any] = x + scale * grad __SCREAMING_SNAKE_CASE : Any = self.reset_xa(_lowerCamelCase , _lowerCamelCase , self.action_dim ) __SCREAMING_SNAKE_CASE : Dict = self.unet(x.permute(0 , 2 , 1 ) , _lowerCamelCase ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg __SCREAMING_SNAKE_CASE : Tuple = self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , predict_epsilon=_lowerCamelCase )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) __SCREAMING_SNAKE_CASE : str = self.reset_xa(_lowerCamelCase , _lowerCamelCase , self.action_dim ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.to_torch(_lowerCamelCase ) return x, y def __call__( self :Any , _lowerCamelCase :int , _lowerCamelCase :str=6_4 , _lowerCamelCase :Optional[Any]=3_2 , _lowerCamelCase :List[Any]=2 , _lowerCamelCase :Any=0.1 ): # normalize the observations and create batch dimension __SCREAMING_SNAKE_CASE : Union[str, Any] = self.normalize(_lowerCamelCase , '''observations''' ) __SCREAMING_SNAKE_CASE : Dict = obs[None].repeat(_lowerCamelCase , axis=0 ) __SCREAMING_SNAKE_CASE : Optional[int] = {0: self.to_torch(_lowerCamelCase )} __SCREAMING_SNAKE_CASE : Optional[int] = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) __SCREAMING_SNAKE_CASE : Optional[int] = randn_tensor(_lowerCamelCase , device=self.unet.device ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.reset_xa(_lowerCamelCase , _lowerCamelCase , self.action_dim ) __SCREAMING_SNAKE_CASE : str = self.to_torch(_lowerCamelCase ) # run the diffusion process __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.run_diffusion(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # sort output trajectories by value __SCREAMING_SNAKE_CASE : Optional[Any] = y.argsort(0 , descending=_lowerCamelCase ).squeeze() __SCREAMING_SNAKE_CASE : Optional[Any] = x[sorted_idx] __SCREAMING_SNAKE_CASE : Union[str, Any] = sorted_values[:, :, : self.action_dim] __SCREAMING_SNAKE_CASE : Union[str, Any] = actions.detach().cpu().numpy() __SCREAMING_SNAKE_CASE : str = self.de_normalize(_lowerCamelCase , key='''actions''' ) # select the action with the highest value if y is not None: __SCREAMING_SNAKE_CASE : Optional[int] = 0 else: # if we didn't run value guiding, select a random action __SCREAMING_SNAKE_CASE : str = np.random.randint(0 , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = denorm_actions[selected_index, 0] return denorm_actions
674
"""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 snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # 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(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) 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 SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = 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. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''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]
674
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { '''configuration_x_clip''': [ '''XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XCLIPConfig''', '''XCLIPTextConfig''', '''XCLIPVisionConfig''', ], '''processing_x_clip''': ['''XCLIPProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XCLIPModel''', '''XCLIPPreTrainedModel''', '''XCLIPTextModel''', '''XCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int = 100 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = (n * (n + 1) // 2) ** 2 __SCREAMING_SNAKE_CASE : Union[str, Any] = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel _lowerCamelCase = '''0.12''' # assumed parallelism: 8 @require_flax @is_staging_test class snake_case ( unittest.TestCase ): @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = TOKEN HfFolder.save_token(_lowerCamelCase ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls :int ): try: delete_repo(token=cls._token , repo_id='''test-model-flax''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-model-flax-org''' ) except HTTPError: pass def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : List[str] = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) __SCREAMING_SNAKE_CASE : Any = FlaxBertModel(_lowerCamelCase ) model.push_to_hub('''test-model-flax''' , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE : Optional[Any] = FlaxBertModel.from_pretrained(f'''{USER}/test-model-flax''' ) __SCREAMING_SNAKE_CASE : Dict = flatten_dict(unfreeze(model.params ) ) __SCREAMING_SNAKE_CASE : Optional[int] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): __SCREAMING_SNAKE_CASE : Optional[int] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_lowerCamelCase , 1e-3 , msg=f'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id='''test-model-flax''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_lowerCamelCase , repo_id='''test-model-flax''' , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE : Dict = FlaxBertModel.from_pretrained(f'''{USER}/test-model-flax''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = flatten_dict(unfreeze(model.params ) ) __SCREAMING_SNAKE_CASE : Dict = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): __SCREAMING_SNAKE_CASE : Any = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_lowerCamelCase , 1e-3 , msg=f'''{key} not identical''' ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Union[str, Any] = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) __SCREAMING_SNAKE_CASE : Any = FlaxBertModel(_lowerCamelCase ) model.push_to_hub('''valid_org/test-model-flax-org''' , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE : str = FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' ) __SCREAMING_SNAKE_CASE : Optional[int] = flatten_dict(unfreeze(model.params ) ) __SCREAMING_SNAKE_CASE : List[Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): __SCREAMING_SNAKE_CASE : List[str] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_lowerCamelCase , 1e-3 , msg=f'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-model-flax-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( _lowerCamelCase , repo_id='''valid_org/test-model-flax-org''' , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE : Tuple = FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' ) __SCREAMING_SNAKE_CASE : int = flatten_dict(unfreeze(model.params ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): __SCREAMING_SNAKE_CASE : Optional[Any] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_lowerCamelCase , 1e-3 , msg=f'''{key} not identical''' ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = True __SCREAMING_SNAKE_CASE : Tuple = flatten_dict(modela.params ) __SCREAMING_SNAKE_CASE : Dict = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1E-4: __SCREAMING_SNAKE_CASE : Tuple = False return models_are_equal @require_flax class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = FlaxBertModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = '''bert''' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(_lowerCamelCase , _lowerCamelCase ) ) with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBertModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = FlaxBertModel.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.assertTrue(check_models_equal(_lowerCamelCase , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) __SCREAMING_SNAKE_CASE : Any = FlaxBertModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = '''bert''' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(_lowerCamelCase , _lowerCamelCase ) , max_shard_size='''10KB''' ) with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = FlaxBertModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBertModel.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.assertTrue(check_models_equal(_lowerCamelCase , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : int = '''bert''' __SCREAMING_SNAKE_CASE : Optional[int] = '''hf-internal-testing/tiny-random-bert-subfolder''' with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Dict = FlaxBertModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = FlaxBertModel.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = '''bert''' __SCREAMING_SNAKE_CASE : List[Any] = '''hf-internal-testing/tiny-random-bert-sharded-subfolder''' with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBertModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = FlaxBertModel.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase )
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" from __future__ import annotations from collections import namedtuple def lowerCAmelCase_ ( lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = namedtuple('''result''' , '''name value''' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('''Only one argument must be 0''' ) elif power < 0: raise ValueError( '''Power cannot be negative in any electrical/electronics system''' ) elif voltage == 0: return result('''voltage''' , power / current ) elif current == 0: return result('''current''' , power / voltage ) elif power == 0: return result('''power''' , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import argparse from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BigBirdConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) if is_trivia_qa: __SCREAMING_SNAKE_CASE : str = BigBirdForQuestionAnswering(lowercase_ ) else: __SCREAMING_SNAKE_CASE : List[str] = BigBirdForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_big_bird(lowercase_ , lowercase_ , is_trivia_qa=lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--big_bird_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT 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.''' ) parser.add_argument( '''--is_trivia_qa''', action='''store_true''', help='''Whether to convert a model with a trivia_qa head.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa )
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib _lowerCamelCase = { '''debug''': logging.DEBUG, '''info''': logging.INFO, '''warning''': logging.WARNING, '''error''': logging.ERROR, '''critical''': logging.CRITICAL, } _lowerCamelCase = logging.WARNING def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = os.getenv('''DATASETS_VERBOSITY''' , lowercase_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'''Unknown option DATASETS_VERBOSITY={env_level_str}, ''' F'''has to be one of: { ', '.join(log_levels.keys() ) }''' ) return _default_log_level def lowerCAmelCase_ ( ): '''simple docstring''' return __name__.split('''.''' )[0] def lowerCAmelCase_ ( ): '''simple docstring''' return logging.getLogger(_get_library_name() ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def lowerCAmelCase_ ( lowercase_ : Optional[str] = None ): '''simple docstring''' if name is None: __SCREAMING_SNAKE_CASE : str = _get_library_name() return logging.getLogger(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' return _get_library_root_logger().getEffectiveLevel() def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' _get_library_root_logger().setLevel(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' return set_verbosity(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' return set_verbosity(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' return set_verbosity(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' return set_verbosity(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = False def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class snake_case : def __init__( self :str , *_lowerCamelCase :List[Any] , **_lowerCamelCase :Any ): # pylint: disable=unused-argument __SCREAMING_SNAKE_CASE : Optional[int] = args[0] if args else None def __iter__( self :Union[str, Any] ): return iter(self._iterator ) def __getattr__( self :Union[str, Any] , _lowerCamelCase :Optional[Any] ): def empty_fn(*_lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): # pylint: disable=unused-argument return return empty_fn def __enter__( self :List[Any] ): return self def __exit__( self :List[str] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Tuple ): return _lowerCamelCase = True class snake_case : def __call__( self :Dict , *_lowerCamelCase :Union[str, Any] , _lowerCamelCase :str=False , **_lowerCamelCase :Optional[int] ): if _tqdm_active and not disable: return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase ) else: return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int , *_lowerCamelCase :List[Any] , **_lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Tuple = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): if _tqdm_active: return tqdm_lib.tqdm.get_lock() _lowerCamelCase = _tqdm_cls() def lowerCAmelCase_ ( ): '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def lowerCAmelCase_ ( ): '''simple docstring''' global _tqdm_active __SCREAMING_SNAKE_CASE : Tuple = True def lowerCAmelCase_ ( ): '''simple docstring''' global _tqdm_active __SCREAMING_SNAKE_CASE : List[Any] = False
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : list ): '''simple docstring''' if len(lowercase_ ) <= 1: return [tuple(lowercase_ )] __SCREAMING_SNAKE_CASE : Any = [] def generate(lowercase_ : int , lowercase_ : list ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , lowercase_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = arr[k - 1], arr[i] else: # k is odd __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = arr[k - 1], arr[0] generate(k - 1 , lowercase_ ) generate(len(lowercase_ ) , lowercase_ ) return res if __name__ == "__main__": _lowerCamelCase = input('''Enter numbers separated by a comma:\n''').strip() _lowerCamelCase = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
674
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_pegasus import PegasusTokenizer else: _lowerCamelCase = None _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = '''▁''' _lowerCamelCase = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} _lowerCamelCase = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''}, '''tokenizer_file''': { '''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/tokenizer.json''' }, } _lowerCamelCase = { '''google/pegasus-xsum''': 5_12, } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = PegasusTokenizer lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :List[Any] , _lowerCamelCase :Any=None , _lowerCamelCase :Any=None , _lowerCamelCase :Any="<pad>" , _lowerCamelCase :Dict="</s>" , _lowerCamelCase :List[str]="<unk>" , _lowerCamelCase :str="<mask_2>" , _lowerCamelCase :List[Any]="<mask_1>" , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[str]=1_0_3 , **_lowerCamelCase :Dict , ): __SCREAMING_SNAKE_CASE : str = offset if additional_special_tokens is not None: if not isinstance(_lowerCamelCase , _lowerCamelCase ): raise TypeError( f'''additional_special_tokens should be of type {type(_lowerCamelCase )}, but is''' f''' {type(_lowerCamelCase )}''' ) __SCREAMING_SNAKE_CASE : List[Any] = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'''<unk_{i}>''' for i in range(len(_lowerCamelCase ) , self.offset - 1 ) ] if len(set(_lowerCamelCase ) ) != len(_lowerCamelCase ): raise ValueError( '''Please make sure that the provided additional_special_tokens do not contain an incorrectly''' f''' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.''' ) __SCREAMING_SNAKE_CASE : str = additional_special_tokens_extended else: __SCREAMING_SNAKE_CASE : Optional[Any] = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'''<unk_{i}>''' for i in range(2 , self.offset )] super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , pad_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , mask_token=_lowerCamelCase , mask_token_sent=_lowerCamelCase , offset=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : List[Any] = vocab_file __SCREAMING_SNAKE_CASE : int = False if not self.vocab_file else True def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Union[str, Any] = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special if all_special_ids != set(range(len(self.additional_special_tokens ) + 3 ) ): raise ValueError( '''There should be 3 special tokens: mask_token, pad_token, and eos_token +''' f''' {len(self.additional_special_tokens )} additional_special_tokens, but got {all_special_ids}''' ) return [1 if x in all_special_ids else 0 for x in seq] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List , _lowerCamelCase :Optional[List] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return self._special_token_mask(_lowerCamelCase ) elif token_ids_a is None: return self._special_token_mask(_lowerCamelCase ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Any , _lowerCamelCase :Any=None ): if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : Dict = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ): copyfile(self.vocab_file , _lowerCamelCase ) return (out_vocab_file,)
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path _lowerCamelCase = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) _lowerCamelCase = [ord(letter) for letter in string.ascii_lowercase] _lowerCamelCase = {ord(char) for char in VALID_CHARS} _lowerCamelCase = ["the", "be", "to", "of", "and", "in", "that", "have"] def lowerCAmelCase_ ( lowercase_ : list[int] , lowercase_ : tuple[int, ...] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = "" __SCREAMING_SNAKE_CASE : int __SCREAMING_SNAKE_CASE : int __SCREAMING_SNAKE_CASE : int for keychar, cipherchar in zip(cycle(lowercase_ ) , lowercase_ ): __SCREAMING_SNAKE_CASE : List[str] = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(lowercase_ ) return decoded def lowerCAmelCase_ ( lowercase_ : list[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : list[str] = [] for key in product(lowercase_ , repeat=3 ): __SCREAMING_SNAKE_CASE : List[Any] = try_key(lowercase_ , lowercase_ ) if encoded is not None: possibles.append(lowercase_ ) return possibles def lowerCAmelCase_ ( lowercase_ : list[str] , lowercase_ : str ): '''simple docstring''' return [possible for possible in possibles if common_word in possible.lower()] def lowerCAmelCase_ ( lowercase_ : str = "p059_cipher.txt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : list[int] __SCREAMING_SNAKE_CASE : list[str] __SCREAMING_SNAKE_CASE : str __SCREAMING_SNAKE_CASE : str __SCREAMING_SNAKE_CASE : str = Path(lowercase_ ).parent.joinpath(lowercase_ ).read_text(encoding='''utf-8''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = [int(lowercase_ ) for number in data.strip().split(''',''' )] __SCREAMING_SNAKE_CASE : Optional[int] = filter_valid_chars(lowercase_ ) for common_word in COMMON_WORDS: __SCREAMING_SNAKE_CASE : Union[str, Any] = filter_common_word(lowercase_ , lowercase_ ) if len(lowercase_ ) == 1: break __SCREAMING_SNAKE_CASE : List[str] = possibles[0] return sum(ord(lowercase_ ) for char in decoded_text ) if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowerCamelCase = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } _lowerCamelCase = {'''allegro/herbert-base-cased''': 5_14} _lowerCamelCase = {} class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_INIT_CONFIGURATION lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = HerbertTokenizer def __init__( self :Optional[Any] , _lowerCamelCase :Dict=None , _lowerCamelCase :Optional[int]=None , _lowerCamelCase :int=None , _lowerCamelCase :Optional[Any]="<s>" , _lowerCamelCase :str="<unk>" , _lowerCamelCase :Any="<pad>" , _lowerCamelCase :Any="<mask>" , _lowerCamelCase :Tuple="</s>" , **_lowerCamelCase :List[Any] , ): super().__init__( _lowerCamelCase , _lowerCamelCase , tokenizer_file=_lowerCamelCase , cls_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , mask_token=_lowerCamelCase , sep_token=_lowerCamelCase , **_lowerCamelCase , ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Tuple = [self.cls_token_id] __SCREAMING_SNAKE_CASE : int = [self.sep_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 SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) if token_ids_a is None: return [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [self.sep_token_id] __SCREAMING_SNAKE_CASE : str = [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 SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): __SCREAMING_SNAKE_CASE : int = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
674
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" from __future__ import annotations import inspect import unittest import numpy as np from transformers import DeiTConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, TFDeiTModel, ) from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self :Any , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=1_3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=2 , _lowerCamelCase :List[str]=3 , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :Optional[Any]=3_2 , _lowerCamelCase :str=2 , _lowerCamelCase :Dict=4 , _lowerCamelCase :Union[str, Any]=3_7 , _lowerCamelCase :Union[str, Any]="gelu" , _lowerCamelCase :str=0.1 , _lowerCamelCase :Dict=0.1 , _lowerCamelCase :int=1_0 , _lowerCamelCase :Optional[int]=0.0_2 , _lowerCamelCase :List[str]=3 , _lowerCamelCase :List[Any]=None , _lowerCamelCase :int=2 , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = parent __SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size __SCREAMING_SNAKE_CASE : List[Any] = image_size __SCREAMING_SNAKE_CASE : List[str] = patch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : int = is_training __SCREAMING_SNAKE_CASE : List[str] = use_labels __SCREAMING_SNAKE_CASE : str = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : Dict = num_attention_heads __SCREAMING_SNAKE_CASE : List[Any] = intermediate_size __SCREAMING_SNAKE_CASE : Dict = hidden_act __SCREAMING_SNAKE_CASE : str = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Tuple = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Optional[int] = type_sequence_label_size __SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range __SCREAMING_SNAKE_CASE : Optional[int] = scope __SCREAMING_SNAKE_CASE : Any = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) __SCREAMING_SNAKE_CASE : Union[str, Any] = (image_size // patch_size) ** 2 __SCREAMING_SNAKE_CASE : Dict = num_patches + 2 def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE : str = None if self.use_labels: __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : Dict = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self :int ): return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[Any] , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Tuple = TFDeiTModel(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :List[str] , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Tuple = TFDeiTForMaskedImageModeling(config=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(_lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __SCREAMING_SNAKE_CASE : Any = 1 __SCREAMING_SNAKE_CASE : int = TFDeiTForMaskedImageModeling(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE : List[str] = model(_lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Tuple , _lowerCamelCase :int , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Tuple = self.type_sequence_label_size __SCREAMING_SNAKE_CASE : Optional[Any] = TFDeiTForImageClassification(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __SCREAMING_SNAKE_CASE : int = 1 __SCREAMING_SNAKE_CASE : Optional[int] = TFDeiTForImageClassification(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[str] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = config_and_inputs __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = ( ( TFDeiTModel, TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher, TFDeiTForMaskedImageModeling, ) if is_tf_available() else () ) lowerCamelCase__ = ( { '''feature-extraction''': TFDeiTModel, '''image-classification''': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher), } if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Tuple = TFDeiTModelTester(self ) __SCREAMING_SNAKE_CASE : List[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): self.config_tester.run_common_tests() @unittest.skip(reason='''DeiT does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :str ): pass def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) __SCREAMING_SNAKE_CASE : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , tf.keras.layers.Dense ) ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Optional[Any] = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : str = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :int=False ): __SCREAMING_SNAKE_CASE : Tuple = super()._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) if return_labels: if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call ).parameters: del inputs_dict["labels"] return inputs_dict @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Dict = TFDeiTModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return ( DeiTImageProcessor.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = TFDeiTForImageClassificationWithTeacher.from_pretrained('''facebook/deit-base-distilled-patch16-224''' ) __SCREAMING_SNAKE_CASE : List[str] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(images=_lowerCamelCase , return_tensors='''tf''' ) # forward pass __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # verify the logits __SCREAMING_SNAKE_CASE : List[str] = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1] ) self.assertTrue(np.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" from maths.prime_factors import prime_factors def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' if not isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : str = F'''Input value of [number={number}] must be an integer''' raise TypeError(lowercase_ ) if number < 1: raise ValueError('''Input must be a positive integer''' ) return -1 if len(prime_factors(lowercase_ ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case ( __UpperCAmelCase ): def __init__( self :Dict , _lowerCamelCase :Dict , _lowerCamelCase :str=1_3 , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Tuple=True , _lowerCamelCase :int=True , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :int=9_9 , _lowerCamelCase :Optional[int]=3_2 , _lowerCamelCase :Tuple=5 , _lowerCamelCase :List[Any]=4 , _lowerCamelCase :Union[str, Any]=3_7 , _lowerCamelCase :List[Any]="gelu" , _lowerCamelCase :Union[str, Any]=0.1 , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :Any=5_1_2 , _lowerCamelCase :List[Any]=1_6 , _lowerCamelCase :Optional[int]=2 , _lowerCamelCase :Optional[int]=0.0_2 , _lowerCamelCase :int=False , _lowerCamelCase :Dict=True , _lowerCamelCase :List[Any]="None" , _lowerCamelCase :List[str]=3 , _lowerCamelCase :Optional[int]=4 , _lowerCamelCase :Tuple=None , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = parent __SCREAMING_SNAKE_CASE : List[str] = batch_size __SCREAMING_SNAKE_CASE : List[str] = seq_length __SCREAMING_SNAKE_CASE : List[Any] = is_training __SCREAMING_SNAKE_CASE : Any = use_input_mask __SCREAMING_SNAKE_CASE : Optional[int] = use_token_type_ids __SCREAMING_SNAKE_CASE : Optional[int] = use_labels __SCREAMING_SNAKE_CASE : Dict = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : Union[str, Any] = num_hidden_layers __SCREAMING_SNAKE_CASE : Tuple = num_attention_heads __SCREAMING_SNAKE_CASE : List[Any] = intermediate_size __SCREAMING_SNAKE_CASE : List[str] = hidden_act __SCREAMING_SNAKE_CASE : Dict = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = type_vocab_size __SCREAMING_SNAKE_CASE : str = type_sequence_label_size __SCREAMING_SNAKE_CASE : Tuple = initializer_range __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Dict = num_choices __SCREAMING_SNAKE_CASE : Any = relative_attention __SCREAMING_SNAKE_CASE : Any = position_biased_input __SCREAMING_SNAKE_CASE : Dict = pos_att_type __SCREAMING_SNAKE_CASE : Optional[int] = scope def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE : Tuple = None if self.use_input_mask: __SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) __SCREAMING_SNAKE_CASE : List[str] = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE : Optional[Any] = None __SCREAMING_SNAKE_CASE : str = None __SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_labels: __SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return DebertaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : List[Any] = self.get_config() __SCREAMING_SNAKE_CASE : Optional[Any] = 3_0_0 return config def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :str ): self.parent.assertListEqual(list(result.loss.size() ) , [] ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :List[str] , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :int , _lowerCamelCase :Any , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : str = DebertaModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : List[str] = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , token_type_ids=_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :List[Any] , _lowerCamelCase :int , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : Tuple = DebertaForMaskedLM(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[int] , _lowerCamelCase :str , _lowerCamelCase :List[Any] , _lowerCamelCase :str , _lowerCamelCase :int , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Tuple = self.num_labels __SCREAMING_SNAKE_CASE : List[Any] = DebertaForSequenceClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Tuple = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :int , _lowerCamelCase :List[Any] , _lowerCamelCase :Any , _lowerCamelCase :Any , _lowerCamelCase :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Any = self.num_labels __SCREAMING_SNAKE_CASE : List[str] = DebertaForTokenClassification(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = DebertaForQuestionAnswering(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : Any = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , start_positions=_lowerCamelCase , end_positions=_lowerCamelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) : Union[str, Any] = config_and_inputs __SCREAMING_SNAKE_CASE : Optional[Any] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase__ = ( { '''feature-extraction''': DebertaModel, '''fill-mask''': DebertaForMaskedLM, '''question-answering''': DebertaForQuestionAnswering, '''text-classification''': DebertaForSequenceClassification, '''token-classification''': DebertaForTokenClassification, '''zero-shot''': DebertaForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ = True lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[int] = DebertaModelTester(self ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*_lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = DebertaModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @require_torch @require_sentencepiece @require_tokenizers class snake_case ( unittest.TestCase ): @unittest.skip(reason='''Model not available yet''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = DebertaModel.from_pretrained('''microsoft/deberta-base''' ) __SCREAMING_SNAKE_CASE : str = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(_lowerCamelCase , attention_mask=_lowerCamelCase )[0] # compare the actual values for a slice. __SCREAMING_SNAKE_CASE : str = torch.tensor( [[[-0.5_9_8_6, -0.8_0_5_5, -0.8_4_6_2], [1.4_4_8_4, -0.9_3_4_8, -0.8_0_5_9], [0.3_1_2_3, 0.0_0_3_2, -1.4_1_3_1]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , _lowerCamelCase , atol=1e-4 ) , f'''{output[:, 1:4, 1:4]}''' )
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" from __future__ import annotations import os from typing import Any import requests _lowerCamelCase = '''https://api.github.com''' # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user _lowerCamelCase = BASE_URL + '''/user''' # https://github.com/settings/tokens _lowerCamelCase = os.environ.get('''USER_TOKEN''', '''''') def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = { '''Authorization''': F'''token {auth_token}''', '''Accept''': '''application/vnd.github.v3+json''', } return requests.get(lowercase_ , headers=lowercase_ ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f'{key}: {value}') else: raise ValueError('''\'USER_TOKEN\' field cannot be empty.''')
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""simple docstring""" import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = MgpstrTokenizer lowerCamelCase__ = False lowerCamelCase__ = {} lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :str ): super().setUp() # fmt: off __SCREAMING_SNAKE_CASE : int = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''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'''] # fmt: on __SCREAMING_SNAKE_CASE : Any = dict(zip(_lowerCamelCase , range(len(_lowerCamelCase ) ) ) ) __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(_lowerCamelCase ) + '''\n''' ) def SCREAMING_SNAKE_CASE_ ( self :str , **_lowerCamelCase :List[Any] ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Dict = '''tester''' __SCREAMING_SNAKE_CASE : Dict = '''tester''' return input_text, output_text @unittest.skip('''MGP-STR always lower cases letters.''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizers(do_lower_case=_lowerCamelCase ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __SCREAMING_SNAKE_CASE : Optional[Any] = '''[SPECIAL_TOKEN]''' tokenizer.add_special_tokens({'''cls_token''': special_token} ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.encode([special_token] , add_special_tokens=_lowerCamelCase ) self.assertEqual(len(_lowerCamelCase ) , 1 ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.decode(_lowerCamelCase , skip_special_tokens=_lowerCamelCase ) self.assertTrue(special_token not in decoded ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Any = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_input_output_texts(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer.convert_tokens_to_ids(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = tokenizer.encode(_lowerCamelCase , add_special_tokens=_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertNotEqual(len(_lowerCamelCase ) , 0 ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.decode(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(text_a.replace(''' ''' , '''''' ) , _lowerCamelCase ) @unittest.skip('''MGP-STR tokenizer only handles one sequence.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass
674
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = LayoutLMTokenizer lowerCamelCase__ = LayoutLMTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def SCREAMING_SNAKE_CASE_ ( self :str ): super().setUp() __SCREAMING_SNAKE_CASE : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , **_lowerCamelCase :Any ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = '''UNwant\u00E9d,running''' __SCREAMING_SNAKE_CASE : Union[str, Any] = '''unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) __SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_lowerCamelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [7, 4, 5, 1_0, 8, 9] ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass
674
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __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 : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
"""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 _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): 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 SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' assert ( isinstance(lowercase_ , lowercase_ ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = 1, 1 for _ in range(number_of_steps - 1 ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class snake_case : def SCREAMING_SNAKE_CASE_ ( self :Any ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( sample_size=3_2 , layers_per_block=1 , block_out_channels=[3_2, 6_4] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=3 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0_0_0_1 , beta_end=0.0_2 , thresholding=_lowerCamelCase , dynamic_thresholding_ratio=0.9_5 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def SCREAMING_SNAKE_CASE_ ( self :Tuple ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = UNetaDConditionModel( sample_size=3_2 , layers_per_block=[1, 2] , block_out_channels=[3_2, 6_4] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=6 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , class_embed_type='''timestep''' , mid_block_scale_factor=1.4_1_4 , time_embedding_act_fn='''gelu''' , time_embedding_dim=3_2 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0_0_0_1 , beta_end=0.0_2 , thresholding=_lowerCamelCase , dynamic_thresholding_ratio=0.9_5 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[str] = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0_0_0_1 , beta_end=0.0_2 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : int = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Optional[int] = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''prompt'''] __SCREAMING_SNAKE_CASE : Tuple = inputs['''generator'''] __SCREAMING_SNAKE_CASE : Optional[Any] = inputs['''num_inference_steps'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = inputs['''output_type'''] if "image" in inputs: __SCREAMING_SNAKE_CASE : Tuple = inputs['''image'''] else: __SCREAMING_SNAKE_CASE : Tuple = None if "mask_image" in inputs: __SCREAMING_SNAKE_CASE : Dict = inputs['''mask_image'''] else: __SCREAMING_SNAKE_CASE : str = None if "original_image" in inputs: __SCREAMING_SNAKE_CASE : Union[str, Any] = inputs['''original_image'''] else: __SCREAMING_SNAKE_CASE : Tuple = None __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = pipe.encode_prompt(_lowerCamelCase ) # inputs with prompt converted to embeddings __SCREAMING_SNAKE_CASE : Optional[int] = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: __SCREAMING_SNAKE_CASE : Tuple = image if mask_image is not None: __SCREAMING_SNAKE_CASE : Optional[Any] = mask_image if original_image is not None: __SCREAMING_SNAKE_CASE : str = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = pipe(**_lowerCamelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class.from_pretrained(_lowerCamelCase ) pipe_loaded.to(_lowerCamelCase ) pipe_loaded.set_progress_bar_config(disable=_lowerCamelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(_lowerCamelCase , _lowerCamelCase ) is None , f'''`{optional_component}` did not stay set to None after loading.''' , ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = inputs['''generator'''] __SCREAMING_SNAKE_CASE : List[str] = inputs['''num_inference_steps'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = inputs['''output_type'''] # inputs with prompt converted to embeddings __SCREAMING_SNAKE_CASE : Union[str, Any] = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: __SCREAMING_SNAKE_CASE : int = image if mask_image is not None: __SCREAMING_SNAKE_CASE : Optional[Any] = mask_image if original_image is not None: __SCREAMING_SNAKE_CASE : Tuple = original_image __SCREAMING_SNAKE_CASE : List[Any] = pipe_loaded(**_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : Any = np.abs(to_np(_lowerCamelCase ) - to_np(_lowerCamelCase ) ).max() self.assertLess(_lowerCamelCase , 1e-4 ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() __SCREAMING_SNAKE_CASE : str = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = pipe(**_lowerCamelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = self.pipeline_class.from_pretrained(_lowerCamelCase ) pipe_loaded.to(_lowerCamelCase ) pipe_loaded.set_progress_bar_config(disable=_lowerCamelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = pipe_loaded(**_lowerCamelCase )[0] __SCREAMING_SNAKE_CASE : Optional[int] = np.abs(to_np(_lowerCamelCase ) - to_np(_lowerCamelCase ) ).max() self.assertLess(_lowerCamelCase , 1e-4 )
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' random.seed(lowercase_ ) np.random.seed(lowercase_ ) torch.manual_seed(lowercase_ ) torch.cuda.manual_seed_all(lowercase_ ) # ^^ safe to call this function even if cuda is not available class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :Iterable[torch.nn.Parameter] , _lowerCamelCase :float = 0.9_9_9_9 , _lowerCamelCase :float = 0.0 , _lowerCamelCase :int = 0 , _lowerCamelCase :bool = False , _lowerCamelCase :Union[float, int] = 1.0 , _lowerCamelCase :Union[float, int] = 2 / 3 , _lowerCamelCase :Optional[Any] = None , _lowerCamelCase :Dict[str, Any] = None , **_lowerCamelCase :Any , ): if isinstance(_lowerCamelCase , torch.nn.Module ): __SCREAMING_SNAKE_CASE : int = ( '''Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ''' '''Please pass the parameters of the module instead.''' ) deprecate( '''passing a `torch.nn.Module` to `ExponentialMovingAverage`''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : List[Any] = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility __SCREAMING_SNAKE_CASE : Optional[int] = True if kwargs.get('''max_value''' , _lowerCamelCase ) is not None: __SCREAMING_SNAKE_CASE : Tuple = '''The `max_value` argument is deprecated. Please use `decay` instead.''' deprecate('''max_value''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = kwargs['''max_value'''] if kwargs.get('''min_value''' , _lowerCamelCase ) is not None: __SCREAMING_SNAKE_CASE : List[Any] = '''The `min_value` argument is deprecated. Please use `min_decay` instead.''' deprecate('''min_value''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = kwargs['''min_value'''] __SCREAMING_SNAKE_CASE : Optional[int] = list(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = [p.clone().detach() for p in parameters] if kwargs.get('''device''' , _lowerCamelCase ) is not None: __SCREAMING_SNAKE_CASE : Union[str, Any] = '''The `device` argument is deprecated. Please use `to` instead.''' deprecate('''device''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase ) self.to(device=kwargs['''device'''] ) __SCREAMING_SNAKE_CASE : int = None __SCREAMING_SNAKE_CASE : Tuple = decay __SCREAMING_SNAKE_CASE : Any = min_decay __SCREAMING_SNAKE_CASE : Optional[int] = update_after_step __SCREAMING_SNAKE_CASE : Optional[Any] = use_ema_warmup __SCREAMING_SNAKE_CASE : str = inv_gamma __SCREAMING_SNAKE_CASE : Tuple = power __SCREAMING_SNAKE_CASE : Any = 0 __SCREAMING_SNAKE_CASE : str = None # set in `step()` __SCREAMING_SNAKE_CASE : Dict = model_cls __SCREAMING_SNAKE_CASE : List[str] = model_config @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Any , _lowerCamelCase :str , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = model_cls.load_config(_lowerCamelCase , return_unused_kwargs=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model_cls.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = cls(model.parameters() , model_cls=_lowerCamelCase , model_config=model.config ) ema_model.load_state_dict(_lowerCamelCase ) return ema_model def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Optional[int] ): if self.model_cls is None: raise ValueError('''`save_pretrained` can only be used if `model_cls` was defined at __init__.''' ) if self.model_config is None: raise ValueError('''`save_pretrained` can only be used if `model_config` was defined at __init__.''' ) __SCREAMING_SNAKE_CASE : List[str] = self.model_cls.from_config(self.model_config ) __SCREAMING_SNAKE_CASE : List[str] = self.state_dict() state_dict.pop('''shadow_params''' , _lowerCamelCase ) model.register_to_config(**_lowerCamelCase ) self.copy_to(model.parameters() ) model.save_pretrained(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : Dict = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: __SCREAMING_SNAKE_CASE : List[str] = 1 - (1 + step / self.inv_gamma) ** -self.power else: __SCREAMING_SNAKE_CASE : Tuple = (1 + step) / (1_0 + step) __SCREAMING_SNAKE_CASE : List[Any] = min(_lowerCamelCase , self.decay ) # make sure decay is not smaller than min_decay __SCREAMING_SNAKE_CASE : Any = max(_lowerCamelCase , self.min_decay ) return cur_decay_value @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Iterable[torch.nn.Parameter] ): if isinstance(_lowerCamelCase , torch.nn.Module ): __SCREAMING_SNAKE_CASE : List[Any] = ( '''Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ''' '''Please pass the parameters of the module instead.''' ) deprecate( '''passing a `torch.nn.Module` to `ExponentialMovingAverage.step`''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : str = parameters.parameters() __SCREAMING_SNAKE_CASE : Union[str, Any] = list(_lowerCamelCase ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_decay(self.optimization_step ) __SCREAMING_SNAKE_CASE : int = decay __SCREAMING_SNAKE_CASE : List[Any] = 1 - decay __SCREAMING_SNAKE_CASE : List[Any] = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , _lowerCamelCase ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): __SCREAMING_SNAKE_CASE : Any = deepspeed.zero.GatheredParameters(_lowerCamelCase , modifier_rank=_lowerCamelCase ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Iterable[torch.nn.Parameter] ): __SCREAMING_SNAKE_CASE : Any = list(_lowerCamelCase ) for s_param, param in zip(self.shadow_params , _lowerCamelCase ): param.data.copy_(s_param.to(param.device ).data ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=None ): __SCREAMING_SNAKE_CASE : List[str] = [ p.to(device=_lowerCamelCase , dtype=_lowerCamelCase ) if p.is_floating_point() else p.to(device=_lowerCamelCase ) for p in self.shadow_params ] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Iterable[torch.nn.Parameter] ): __SCREAMING_SNAKE_CASE : Tuple = [param.detach().cpu().clone() for param in parameters] def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Iterable[torch.nn.Parameter] ): if self.temp_stored_params is None: raise RuntimeError('''This ExponentialMovingAverage has no `store()`ed weights ''' '''to `restore()`''' ) for c_param, param in zip(self.temp_stored_params , _lowerCamelCase ): param.data.copy_(c_param.data ) # Better memory-wise. __SCREAMING_SNAKE_CASE : Dict = None def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = copy.deepcopy(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = state_dict.get('''decay''' , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('''Decay must be between 0 and 1''' ) __SCREAMING_SNAKE_CASE : Dict = state_dict.get('''min_decay''' , self.min_decay ) if not isinstance(self.min_decay , _lowerCamelCase ): raise ValueError('''Invalid min_decay''' ) __SCREAMING_SNAKE_CASE : List[str] = state_dict.get('''optimization_step''' , self.optimization_step ) if not isinstance(self.optimization_step , _lowerCamelCase ): raise ValueError('''Invalid optimization_step''' ) __SCREAMING_SNAKE_CASE : Any = state_dict.get('''update_after_step''' , self.update_after_step ) if not isinstance(self.update_after_step , _lowerCamelCase ): raise ValueError('''Invalid update_after_step''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.get('''use_ema_warmup''' , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , _lowerCamelCase ): raise ValueError('''Invalid use_ema_warmup''' ) __SCREAMING_SNAKE_CASE : int = state_dict.get('''inv_gamma''' , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError('''Invalid inv_gamma''' ) __SCREAMING_SNAKE_CASE : Tuple = state_dict.get('''power''' , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError('''Invalid power''' ) __SCREAMING_SNAKE_CASE : Optional[int] = state_dict.get('''shadow_params''' , _lowerCamelCase ) if shadow_params is not None: __SCREAMING_SNAKE_CASE : str = shadow_params if not isinstance(self.shadow_params , _lowerCamelCase ): raise ValueError('''shadow_params must be a list''' ) if not all(isinstance(_lowerCamelCase , torch.Tensor ) for p in self.shadow_params ): raise ValueError('''shadow_params must all be Tensors''' )
674
"""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 snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # 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(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) 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 SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = 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. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''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]
674
1
"""simple docstring""" import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' if isinstance(lowercase_ , collections.abc.Iterable ): return x return (x, x) @require_flax class snake_case : def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Tuple ): pass def SCREAMING_SNAKE_CASE_ ( self :str ): pass def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :np.ndarray , _lowerCamelCase :np.ndarray , _lowerCamelCase :float ): __SCREAMING_SNAKE_CASE : Dict = np.abs((a - b) ).max() self.assertLessEqual(_lowerCamelCase , _lowerCamelCase , f'''Difference between torch and flax is {diff} (>= {tol}).''' ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[str] , _lowerCamelCase :Dict , _lowerCamelCase :Optional[int] , _lowerCamelCase :List[str] , _lowerCamelCase :int=None , **_lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderConfig.from_vision_text_configs(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = FlaxVisionTextDualEncoderModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model(input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase ) self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[str] , _lowerCamelCase :Tuple , _lowerCamelCase :List[str] , _lowerCamelCase :Dict , _lowerCamelCase :int=None , **_lowerCamelCase :int ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_vision_text_model(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = {'''vision_model''': vision_model, '''text_model''': text_model} __SCREAMING_SNAKE_CASE : Optional[int] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model(input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase ) self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], model.config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Dict , _lowerCamelCase :Optional[int] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :List[Any]=None , **_lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.get_vision_text_model(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = {'''vision_model''': vision_model, '''text_model''': text_model} __SCREAMING_SNAKE_CASE : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = FlaxVisionTextDualEncoderModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = model(input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = after_output[0] __SCREAMING_SNAKE_CASE : Tuple = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_lowerCamelCase , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :List[Any] , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :List[str] , _lowerCamelCase :List[Any]=None , **_lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = self.get_vision_text_model(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = {'''vision_model''': vision_model, '''text_model''': text_model} __SCREAMING_SNAKE_CASE : str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model( input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase , output_attentions=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = output.vision_model_output.attentions self.assertEqual(len(_lowerCamelCase ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) __SCREAMING_SNAKE_CASE : Tuple = to_atuple(vision_model.config.image_size ) __SCREAMING_SNAKE_CASE : List[Any] = to_atuple(vision_model.config.patch_size ) __SCREAMING_SNAKE_CASE : Tuple = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) __SCREAMING_SNAKE_CASE : int = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) __SCREAMING_SNAKE_CASE : Optional[int] = output.text_model_output.attentions self.assertEqual(len(_lowerCamelCase ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Any , _lowerCamelCase :int ): pt_model.to(_lowerCamelCase ) pt_model.eval() # prepare inputs __SCREAMING_SNAKE_CASE : Union[str, Any] = inputs_dict __SCREAMING_SNAKE_CASE : Tuple = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): __SCREAMING_SNAKE_CASE : Union[str, Any] = pt_model(**_lowerCamelCase ).to_tuple() __SCREAMING_SNAKE_CASE : Optional[Any] = fx_model(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(_lowerCamelCase , pt_output.numpy() , 4e-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = fx_model_loaded(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(_lowerCamelCase , pt_output.numpy() , 4e-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = VisionTextDualEncoderModel.from_pretrained(_lowerCamelCase , from_flax=_lowerCamelCase ) pt_model_loaded.to(_lowerCamelCase ) pt_model_loaded.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE : Optional[int] = pt_model_loaded(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(_lowerCamelCase , pt_output_loaded.numpy() , 4e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :str , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Any = VisionTextDualEncoderConfig.from_vision_text_configs(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = VisionTextDualEncoderModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = FlaxVisionTextDualEncoderModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = fx_state self.check_pt_flax_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderConfig.from_vision_text_configs(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = FlaxVisionTextDualEncoderModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = load_flax_weights_in_pytorch_model(_lowerCamelCase , fx_model.params ) self.check_pt_flax_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : str = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() self.check_save_load(**_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_lowerCamelCase ) @is_pt_flax_cross_test def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Union[str, Any] = config_inputs_dict.pop('''vision_config''' ) __SCREAMING_SNAKE_CASE : Optional[int] = config_inputs_dict.pop('''text_config''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = config_inputs_dict self.check_equivalence_pt_to_flax(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.check_equivalence_flax_to_pt(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.get_pretrained_model_and_inputs() __SCREAMING_SNAKE_CASE : List[Any] = model_a(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = model_a(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = after_outputs[0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_lowerCamelCase , 1e-5 ) @require_flax class snake_case ( __UpperCAmelCase , unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-vit''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=_lowerCamelCase , text_from_pt=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : List[str] = 1_3 __SCREAMING_SNAKE_CASE : Any = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) __SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) __SCREAMING_SNAKE_CASE : Optional[Any] = random_attention_mask([batch_size, 4] ) __SCREAMING_SNAKE_CASE : List[str] = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Dict = FlaxViTModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = FlaxBertModel(_lowerCamelCase ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : List[Any] = FlaxViTModelTester(self ) __SCREAMING_SNAKE_CASE : Dict = FlaxBertModelTester(self ) __SCREAMING_SNAKE_CASE : Tuple = vit_model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = bert_model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = vision_config_and_inputs __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class snake_case ( __UpperCAmelCase , unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Optional[int] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-clip''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=_lowerCamelCase , text_from_pt=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = 1_3 __SCREAMING_SNAKE_CASE : List[str] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) __SCREAMING_SNAKE_CASE : List[str] = random_attention_mask([batch_size, 4] ) __SCREAMING_SNAKE_CASE : Optional[Any] = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[str] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : List[Any] = FlaxCLIPVisionModel(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = FlaxBertModel(_lowerCamelCase ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : List[Any] = FlaxCLIPVisionModelTester(self ) __SCREAMING_SNAKE_CASE : int = FlaxBertModelTester(self ) __SCREAMING_SNAKE_CASE : List[str] = clip_model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = bert_model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = vision_config_and_inputs __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : List[Any] = FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian''' , logit_scale_init_value=1.0 ) __SCREAMING_SNAKE_CASE : List[str] = VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = processor( text=['''una foto di un gatto''', '''una foto di un cane'''] , images=_lowerCamelCase , padding=_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) __SCREAMING_SNAKE_CASE : Dict = np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] ) self.assertTrue(np.allclose(outputs.logits_per_image , _lowerCamelCase , atol=1e-3 ) )
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _lowerCamelCase = '''https://www.indeed.co.in/jobs?q=mobile+app+development&l=''' def lowerCAmelCase_ ( lowercase_ : str = "mumbai" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = BeautifulSoup(requests.get(url + location ).content , '''html.parser''' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('''div''' , attrs={'''data-tn-component''': '''organicJob'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = job.find('''a''' , attrs={'''data-tn-element''': '''jobTitle'''} ).text.strip() __SCREAMING_SNAKE_CASE : Any = job.find('''span''' , {'''class''': '''company'''} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('''Bangalore'''), 1): print(f'Job {i:>2} is {job[0]} at {job[1]}')
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch _lowerCamelCase = True except ImportError: _lowerCamelCase = False try: from torch.hub import _get_torch_home _lowerCamelCase = _get_torch_home() except ImportError: _lowerCamelCase = os.path.expanduser( os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch''')) ) _lowerCamelCase = os.path.join(torch_cache_home, '''transformers''') _lowerCamelCase = '''https://cdn.huggingface.co''' _lowerCamelCase = '''https://s3.amazonaws.com/models.huggingface.co/bert''' _lowerCamelCase = '''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1]) _lowerCamelCase = os.path.join(PATH, '''config.yaml''') _lowerCamelCase = os.path.join(PATH, '''attributes.txt''') _lowerCamelCase = os.path.join(PATH, '''objects.txt''') _lowerCamelCase = os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path) _lowerCamelCase = os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE) _lowerCamelCase = os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE) _lowerCamelCase = '''pytorch_model.bin''' _lowerCamelCase = '''config.yaml''' def lowerCAmelCase_ ( lowercase_ : Optional[int]=OBJECTS , lowercase_ : Any=ATTRIBUTES ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = [] with open(lowercase_ ) as f: for object in f.readlines(): vg_classes.append(object.split(''',''' )[0].lower().strip() ) __SCREAMING_SNAKE_CASE : str = [] with open(lowercase_ ) as f: for object in f.readlines(): vg_attrs.append(object.split(''',''' )[0].lower().strip() ) return vg_classes, vg_attrs def lowerCAmelCase_ ( lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = OrderedDict() with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : str = pkl.load(lowercase_ )['''model'''] for k in copy.deepcopy(list(ckp.keys() ) ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ckp.pop(lowercase_ ) if isinstance(lowercase_ , np.ndarray ): __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase_ ) else: assert isinstance(lowercase_ , torch.tensor ), type(lowercase_ ) __SCREAMING_SNAKE_CASE : int = v return r class snake_case : lowerCamelCase__ = {} def __init__( self :Tuple , _lowerCamelCase :dict , _lowerCamelCase :str = "root" , _lowerCamelCase :List[Any]=0 ): __SCREAMING_SNAKE_CASE : Tuple = name __SCREAMING_SNAKE_CASE : int = level __SCREAMING_SNAKE_CASE : Any = {} for k, v in dictionary.items(): if v is None: raise ValueError() __SCREAMING_SNAKE_CASE : Optional[int] = copy.deepcopy(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = copy.deepcopy(_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = Config(_lowerCamelCase , name=_lowerCamelCase , level=level + 1 ) __SCREAMING_SNAKE_CASE : Dict = v setattr(self , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = d def __repr__( self :Union[str, Any] ): return str(list((self._pointer.keys()) ) ) def __setattr__( self :str , _lowerCamelCase :Optional[int] , _lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = val __SCREAMING_SNAKE_CASE : List[str] = val __SCREAMING_SNAKE_CASE : Union[str, Any] = key.split('''.''' ) __SCREAMING_SNAKE_CASE : Dict = len(_lowerCamelCase ) - 1 __SCREAMING_SNAKE_CASE : str = self._pointer if len(_lowerCamelCase ) > 1: for i, l in enumerate(_lowerCamelCase ): if hasattr(self , _lowerCamelCase ) and isinstance(getattr(self , _lowerCamelCase ) , _lowerCamelCase ): setattr(getattr(self , _lowerCamelCase ) , '''.'''.join(levels[i:] ) , _lowerCamelCase ) if l == last_level: __SCREAMING_SNAKE_CASE : Any = val else: __SCREAMING_SNAKE_CASE : List[Any] = pointer[l] def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self._pointer def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] ): with open(f'''{file_name}''' , '''w''' ) as stream: dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Dict , _lowerCamelCase :Optional[Any] ): with open(f'''{file_name}''' , '''w''' ) as stream: json.dump(_lowerCamelCase , _lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): with open(_lowerCamelCase ) as stream: __SCREAMING_SNAKE_CASE : int = load(_lowerCamelCase , Loader=_lowerCamelCase ) return data def __str__( self :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = ''' ''' if self._name != "root": __SCREAMING_SNAKE_CASE : List[Any] = f'''{t * (self._level-1)}{self._name}:\n''' else: __SCREAMING_SNAKE_CASE : Optional[int] = '''''' __SCREAMING_SNAKE_CASE : Union[str, Any] = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(_lowerCamelCase , _lowerCamelCase ): r += f'''{t * (self._level)}{v}\n''' self._level += 1 else: r += f'''{t * (self._level)}{k}: {v} ({type(_lowerCamelCase ).__name__})\n''' __SCREAMING_SNAKE_CASE : Union[str, Any] = level return r[:-1] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Optional[Any] , _lowerCamelCase :str , **_lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) return cls(_lowerCamelCase ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict , _lowerCamelCase :str , **_lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : Any = kwargs.pop('''cache_dir''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = kwargs.pop('''force_download''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = kwargs.pop('''resume_download''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = kwargs.pop('''proxies''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = kwargs.pop('''local_files_only''' , _lowerCamelCase ) if os.path.isdir(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : str = os.path.join(_lowerCamelCase , _lowerCamelCase ) elif os.path.isfile(_lowerCamelCase ) or is_remote_url(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Tuple = pretrained_model_name_or_path else: __SCREAMING_SNAKE_CASE : Dict = hf_bucket_url(_lowerCamelCase , filename=_lowerCamelCase , use_cdn=_lowerCamelCase ) try: # Load from URL or cache if already cached __SCREAMING_SNAKE_CASE : List[Any] = cached_path( _lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , proxies=_lowerCamelCase , resume_download=_lowerCamelCase , local_files_only=_lowerCamelCase , ) # Load config dict if resolved_config_file is None: raise EnvironmentError __SCREAMING_SNAKE_CASE : List[str] = Config.load_yaml(_lowerCamelCase ) except EnvironmentError: __SCREAMING_SNAKE_CASE : List[str] = '''Can\'t load config for''' raise EnvironmentError(_lowerCamelCase ) if resolved_config_file == config_file: print('''loading configuration file from path''' ) else: print('''loading configuration file cache''' ) return Config.load_yaml(_lowerCamelCase ), kwargs def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = torch.load('''dump.pt''' , map_location=in_tensor.device ) __SCREAMING_SNAKE_CASE : Optional[int] = in_tensor.numpy() __SCREAMING_SNAKE_CASE : Optional[Any] = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(lowercase_ , lowercase_ , rtol=0.01 , atol=0.1 ), ( F'''{sum([1 for x in np.isclose(lowercase_ , lowercase_ , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %''' " element-wise mismatch" ) raise Exception('''tensors are all good''' ) # Hugging face functions below def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = urlparse(lowercase_ ) return parsed.scheme in ("http", "https") def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : str , lowercase_ : str=True ): '''simple docstring''' __SCREAMING_SNAKE_CASE : str = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX __SCREAMING_SNAKE_CASE : Any = '''/''' not in model_id if legacy_format: return F'''{endpoint}/{model_id}-{filename}''' else: return F'''{endpoint}/{model_id}/{filename}''' def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : int , lowercase_ : Union[str, Any]=None , lowercase_ : Optional[int]=0 , lowercase_ : str=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = '''python/{}'''.format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(lowercase_ , lowercase_ ): ua += "; " + "; ".join('''{}/{}'''.format(lowercase_ , lowercase_ ) for k, v in user_agent.items() ) elif isinstance(lowercase_ , lowercase_ ): ua += "; " + user_agent __SCREAMING_SNAKE_CASE : List[Any] = {'''user-agent''': ua} if resume_size > 0: __SCREAMING_SNAKE_CASE : Optional[Any] = '''bytes=%d-''' % (resume_size,) __SCREAMING_SNAKE_CASE : Union[str, Any] = requests.get(lowercase_ , stream=lowercase_ , proxies=lowercase_ , headers=lowercase_ ) if response.status_code == 416: # Range not satisfiable return __SCREAMING_SNAKE_CASE : List[Any] = response.headers.get('''Content-Length''' ) __SCREAMING_SNAKE_CASE : Any = resume_size + int(lowercase_ ) if content_length is not None else None __SCREAMING_SNAKE_CASE : str = tqdm( unit='''B''' , unit_scale=lowercase_ , total=lowercase_ , initial=lowercase_ , desc='''Downloading''' , ) for chunk in response.iter_content(chunk_size=1024 ): if chunk: # filter out keep-alive new chunks progress.update(len(lowercase_ ) ) temp_file.write(lowercase_ ) progress.close() def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int=None , lowercase_ : Dict=False , lowercase_ : Optional[Any]=None , lowercase_ : Any=10 , lowercase_ : List[Any]=False , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]=False , ): '''simple docstring''' if cache_dir is None: __SCREAMING_SNAKE_CASE : str = TRANSFORMERS_CACHE if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : Dict = str(lowercase_ ) os.makedirs(lowercase_ , exist_ok=lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = None if not local_files_only: try: __SCREAMING_SNAKE_CASE : Any = requests.head(lowercase_ , allow_redirects=lowercase_ , proxies=lowercase_ , timeout=lowercase_ ) if response.status_code == 200: __SCREAMING_SNAKE_CASE : Optional[int] = response.headers.get('''ETag''' ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass __SCREAMING_SNAKE_CASE : Optional[int] = url_to_filename(lowercase_ , lowercase_ ) # get cache path to put the file __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(lowercase_ , lowercase_ ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(lowercase_ ): return cache_path else: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ file for file in fnmatch.filter(os.listdir(lowercase_ ) , filename + '''.*''' ) if not file.endswith('''.json''' ) and not file.endswith('''.lock''' ) ] if len(lowercase_ ) > 0: return os.path.join(lowercase_ , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( '''Cannot find the requested files in the cached path and outgoing traffic has been''' ''' disabled. To enable model look-ups and downloads online, set \'local_files_only\'''' ''' to False.''' ) return None # From now on, etag is not None. if os.path.exists(lowercase_ ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. __SCREAMING_SNAKE_CASE : Dict = cache_path + '''.lock''' with FileLock(lowercase_ ): # If the download just completed while the lock was activated. if os.path.exists(lowercase_ ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: __SCREAMING_SNAKE_CASE : List[str] = cache_path + '''.incomplete''' @contextmanager def _resumable_file_manager(): with open(lowercase_ , '''a+b''' ) as f: yield f __SCREAMING_SNAKE_CASE : str = _resumable_file_manager if os.path.exists(lowercase_ ): __SCREAMING_SNAKE_CASE : Any = os.stat(lowercase_ ).st_size else: __SCREAMING_SNAKE_CASE : str = 0 else: __SCREAMING_SNAKE_CASE : List[str] = partial(tempfile.NamedTemporaryFile , dir=lowercase_ , delete=lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( '''%s not found in cache or force_download set to True, downloading to %s''' , lowercase_ , temp_file.name , ) http_get( lowercase_ , lowercase_ , proxies=lowercase_ , resume_size=lowercase_ , user_agent=lowercase_ , ) os.replace(temp_file.name , lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = {'''url''': url, '''etag''': etag} __SCREAMING_SNAKE_CASE : Union[str, Any] = cache_path + '''.json''' with open(lowercase_ , '''w''' ) as meta_file: json.dump(lowercase_ , lowercase_ ) return cache_path def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any=None ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[Any] = url.encode('''utf-8''' ) __SCREAMING_SNAKE_CASE : Any = shaaaa(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = url_hash.hexdigest() if etag: __SCREAMING_SNAKE_CASE : Tuple = etag.encode('''utf-8''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = shaaaa(lowercase_ ) filename += "." + etag_hash.hexdigest() if url.endswith('''.h5''' ): filename += ".h5" return filename def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : Optional[int]=None , lowercase_ : int=False , lowercase_ : Optional[Any]=None , lowercase_ : List[Any]=False , lowercase_ : Any=None , lowercase_ : Optional[int]=False , lowercase_ : Tuple=False , lowercase_ : int=False , ): '''simple docstring''' if cache_dir is None: __SCREAMING_SNAKE_CASE : Optional[Any] = TRANSFORMERS_CACHE if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : Tuple = str(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : Dict = str(lowercase_ ) if is_remote_url(lowercase_ ): # URL, so get it from the cache (downloading if necessary) __SCREAMING_SNAKE_CASE : Any = get_from_cache( lowercase_ , cache_dir=lowercase_ , force_download=lowercase_ , proxies=lowercase_ , resume_download=lowercase_ , user_agent=lowercase_ , local_files_only=lowercase_ , ) elif os.path.exists(lowercase_ ): # File, and it exists. __SCREAMING_SNAKE_CASE : List[str] = url_or_filename elif urlparse(lowercase_ ).scheme == "": # File, but it doesn't exist. raise EnvironmentError('''file {} not found'''.format(lowercase_ ) ) else: # Something unknown raise ValueError('''unable to parse {} as a URL or as a local path'''.format(lowercase_ ) ) if extract_compressed_file: if not is_zipfile(lowercase_ ) and not tarfile.is_tarfile(lowercase_ ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = os.path.split(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = output_file.replace('''.''' , '''-''' ) + '''-extracted''' __SCREAMING_SNAKE_CASE : Dict = os.path.join(lowercase_ , lowercase_ ) if os.path.isdir(lowercase_ ) and os.listdir(lowercase_ ) and not force_extract: return output_path_extracted # Prevent parallel extractions __SCREAMING_SNAKE_CASE : Dict = output_path + '''.lock''' with FileLock(lowercase_ ): shutil.rmtree(lowercase_ , ignore_errors=lowercase_ ) os.makedirs(lowercase_ ) if is_zipfile(lowercase_ ): with ZipFile(lowercase_ , '''r''' ) as zip_file: zip_file.extractall(lowercase_ ) zip_file.close() elif tarfile.is_tarfile(lowercase_ ): __SCREAMING_SNAKE_CASE : Optional[Any] = tarfile.open(lowercase_ ) tar_file.extractall(lowercase_ ) tar_file.close() else: raise EnvironmentError('''Archive format of {} could not be identified'''.format(lowercase_ ) ) return output_path_extracted return output_path def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : List[str]="," ): '''simple docstring''' assert isinstance(lowercase_ , lowercase_ ) if os.path.isfile(lowercase_ ): with open(lowercase_ ) as f: __SCREAMING_SNAKE_CASE : str = eval(f.read() ) else: __SCREAMING_SNAKE_CASE : Any = requests.get(lowercase_ ) try: __SCREAMING_SNAKE_CASE : Optional[int] = requests.json() except Exception: __SCREAMING_SNAKE_CASE : Tuple = req.content.decode() assert data is not None, "could not connect" try: __SCREAMING_SNAKE_CASE : List[Any] = eval(lowercase_ ) except Exception: __SCREAMING_SNAKE_CASE : List[Any] = data.split('''\n''' ) req.close() return data def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = requests.get(lowercase_ ) __SCREAMING_SNAKE_CASE : str = np.array(Image.open(BytesIO(response.content ) ) ) return img def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = url.split('''/''' )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(lowercase_ ) with open(lowercase_ , '''rb''' ) as stream: __SCREAMING_SNAKE_CASE : Tuple = pkl.load(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = weights.pop('''model''' ) __SCREAMING_SNAKE_CASE : str = {} for k, v in model.items(): __SCREAMING_SNAKE_CASE : Optional[int] = torch.from_numpy(lowercase_ ) if "running_var" in k: __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([0] ) __SCREAMING_SNAKE_CASE : List[Any] = k.replace('''running_var''' , '''num_batches_tracked''' ) __SCREAMING_SNAKE_CASE : Dict = zero return new def lowerCAmelCase_ ( ): '''simple docstring''' print(F'''{os.path.abspath(os.path.join(lowercase_ , os.pardir ) )}/demo.ipynb''' ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str]="RGB" ): '''simple docstring''' assert isinstance(lowercase_ , lowercase_ ) if os.path.isfile(lowercase_ ): __SCREAMING_SNAKE_CASE : Any = cva.imread(lowercase_ ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = get_image_from_url(lowercase_ ) assert img is not None, F'''could not connect to: {im}''' __SCREAMING_SNAKE_CASE : List[str] = cva.cvtColor(lowercase_ , cva.COLOR_BGR2RGB ) if input_format == "RGB": __SCREAMING_SNAKE_CASE : List[Any] = img[:, :, ::-1] return img def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int=1 ): '''simple docstring''' return (images[i : i + batch] for i in range(0 , len(lowercase_ ) , lowercase_ ))
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : int ): '''simple docstring''' while b: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = b, a % b return a def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : int ): '''simple docstring''' return a if b == 0 else euclidean_gcd_recursive(lowercase_ , a % b ) def lowerCAmelCase_ ( ): '''simple docstring''' print(F'''euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}''' ) print(F'''euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}''' ) print(F'''euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}''' ) print(F'''euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}''' ) print(F'''euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}''' ) print(F'''euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}''' ) print(F'''euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}''' ) print(F'''euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}''' ) print(F'''euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}''' ) print(F'''euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}''' ) if __name__ == "__main__": main()
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) _lowerCamelCase = logging.getLogger() _lowerCamelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class snake_case ( __UpperCAmelCase ): def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] ): os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = {'''source''': '''What is love ?''', '''target''': '''life'''} __SCREAMING_SNAKE_CASE : Optional[int] = {'''train''': 1_2, '''val''': 2, '''test''': 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: __SCREAMING_SNAKE_CASE : Union[str, Any] = '''\n'''.join([contents[field]] * n_lines[split] ) with open(os.path.join(_lowerCamelCase , f'''{split}.{field}''' ) , '''w''' ) as f: f.write(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int , _lowerCamelCase :str = "pytorch" ): __SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , '''output''' ) __SCREAMING_SNAKE_CASE : List[str] = os.path.join(_lowerCamelCase , '''data''' ) self._create_dummy_data(data_dir=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = f''' --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ '''.split() if gpus > 0: testargs.append(f'''--gpus={gpus}''' ) if is_apex_available(): testargs.append('''--fp16''' ) else: testargs.append('''--gpus=0''' ) testargs.append('''--distributed_backend=ddp_cpu''' ) testargs.append('''--num_processes=2''' ) __SCREAMING_SNAKE_CASE : List[str] = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(_lowerCamelCase , env=self.get_env() ) __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(_lowerCamelCase , '''metrics.json''' ) with open(_lowerCamelCase ) as f: __SCREAMING_SNAKE_CASE : List[Any] = json.load(_lowerCamelCase ) return result @require_torch_gpu def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[int] = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_multi_gpu def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Tuple = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_gpu @require_ray def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Any = self._run_finetune(gpus=1 , distributed_retriever='''ray''' ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 ) @require_torch_multi_gpu @require_ray def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : List[str] = self._run_finetune(gpus=1 , distributed_retriever='''ray''' ) self.assertGreaterEqual(result['''test'''][0]['''test_avg_em'''] , 0.2 )
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, 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 snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = KandinskyVaaInpaintPipeline lowerCamelCase__ = ['''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image'''] lowerCamelCase__ = [ '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''', ] lowerCamelCase__ = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] lowerCamelCase__ = False @property def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return 3_2 @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return 3_2 @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.time_input_dim @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.time_input_dim * 4 @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return 1_0_0 @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[Any] = { '''in_channels''': 9, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''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, } __SCREAMING_SNAKE_CASE : str = UNetaDConditionModel(**_lowerCamelCase ) return model @property def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : List[Any] = VQModel(**self.dummy_movq_kwargs ) return model def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_unet __SCREAMING_SNAKE_CASE : Union[str, Any] = self.dummy_movq __SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''linear''' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , steps_offset=1 , prediction_type='''epsilon''' , thresholding=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :List[str]=0 ): __SCREAMING_SNAKE_CASE : Dict = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _lowerCamelCase ) # create init_image __SCREAMING_SNAKE_CASE : int = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE : int = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('''RGB''' ).resize((2_5_6, 2_5_6) ) # create mask __SCREAMING_SNAKE_CASE : int = np.ones((6_4, 6_4) , dtype=np.floataa ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 if str(_lowerCamelCase ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = { '''image''': init_image, '''mask_image''': mask, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 6_4, '''width''': 6_4, '''num_inference_steps''': 2, '''guidance_scale''': 4.0, '''output_type''': '''np''', } return inputs def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = '''cpu''' __SCREAMING_SNAKE_CASE : str = self.get_dummy_components() __SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = pipe(**self.get_dummy_inputs(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = output.images __SCREAMING_SNAKE_CASE : Any = pipe( **self.get_dummy_inputs(_lowerCamelCase ) , return_dict=_lowerCamelCase , )[0] __SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE : Tuple = image_from_tuple[0, -3:, -3:, -1] print(f'''image.shape {image.shape}''' ) assert image.shape == (1, 6_4, 6_4, 3) __SCREAMING_SNAKE_CASE : List[Any] = np.array( [0.5_0_7_7_5_9_0_3, 0.4_9_5_2_7_1_9_5, 0.4_8_8_2_4_5_4_3, 0.5_0_1_9_2_2_3_7, 0.4_8_6_4_4_9_0_6, 0.4_9_3_7_3_8_1_4, 0.4_7_8_0_5_9_8, 0.4_7_2_3_4_8_2_7, 0.4_8_3_2_7_8_4_8] ) 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()}''' def SCREAMING_SNAKE_CASE_ ( self :Any ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Tuple = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy''' ) __SCREAMING_SNAKE_CASE : int = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) __SCREAMING_SNAKE_CASE : Any = np.ones((7_6_8, 7_6_8) , dtype=np.floataa ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 __SCREAMING_SNAKE_CASE : Optional[int] = '''a hat''' __SCREAMING_SNAKE_CASE : str = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = KandinskyVaaInpaintPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder-inpaint''' , torch_dtype=torch.floataa ) __SCREAMING_SNAKE_CASE : int = pipeline.to(_lowerCamelCase ) pipeline.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.Generator(device='''cpu''' ).manual_seed(0 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = pipe_prior( _lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() __SCREAMING_SNAKE_CASE : Dict = pipeline( image=_lowerCamelCase , mask_image=_lowerCamelCase , image_embeds=_lowerCamelCase , negative_image_embeds=_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , output_type='''np''' , ) __SCREAMING_SNAKE_CASE : Dict = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase )
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''tensor(bool)''': np.bool_, '''tensor(int8)''': np.inta, '''tensor(uint8)''': np.uinta, '''tensor(int16)''': np.intaa, '''tensor(uint16)''': np.uintaa, '''tensor(int32)''': np.intaa, '''tensor(uint32)''': np.uintaa, '''tensor(int64)''': np.intaa, '''tensor(uint64)''': np.uintaa, '''tensor(float16)''': np.floataa, '''tensor(float)''': np.floataa, '''tensor(double)''': np.floataa, } class snake_case : def __init__( self :Tuple , _lowerCamelCase :Tuple=None , **_lowerCamelCase :Optional[Any] ): logger.info('''`diffusers.OnnxRuntimeModel` is experimental and might change in the future.''' ) __SCREAMING_SNAKE_CASE : int = model __SCREAMING_SNAKE_CASE : Tuple = kwargs.get('''model_save_dir''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = kwargs.get('''latest_model_name''' , _lowerCamelCase ) def __call__( self :Dict , **_lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : List[Any] = {k: np.array(_lowerCamelCase ) for k, v in kwargs.items()} return self.model.run(_lowerCamelCase , _lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Union[str, Path] , _lowerCamelCase :Any=None , _lowerCamelCase :Any=None ): if provider is None: logger.info('''No onnxruntime provider specified, using CPUExecutionProvider''' ) __SCREAMING_SNAKE_CASE : List[str] = '''CPUExecutionProvider''' return ort.InferenceSession(_lowerCamelCase , providers=[provider] , sess_options=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Union[str, Path] , _lowerCamelCase :Optional[str] = None , **_lowerCamelCase :List[Any] ): __SCREAMING_SNAKE_CASE : int = file_name if file_name is not None else ONNX_WEIGHTS_NAME __SCREAMING_SNAKE_CASE : List[str] = self.model_save_dir.joinpath(self.latest_model_name ) __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ).joinpath(_lowerCamelCase ) try: shutil.copyfile(_lowerCamelCase , _lowerCamelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) __SCREAMING_SNAKE_CASE : List[str] = self.model_save_dir.joinpath(_lowerCamelCase ) if src_path.exists(): __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(_lowerCamelCase ) try: shutil.copyfile(_lowerCamelCase , _lowerCamelCase ) except shutil.SameFileError: pass def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Union[str, os.PathLike] , **_lowerCamelCase :Optional[int] , ): if os.path.isfile(_lowerCamelCase ): logger.error(f'''Provided path ({save_directory}) should be a directory, not a file''' ) return os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) # saving model weights/files self._save_pretrained(_lowerCamelCase , **_lowerCamelCase ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Union[str, Any] , _lowerCamelCase :Union[str, Path] , _lowerCamelCase :Optional[Union[bool, str, None]] = None , _lowerCamelCase :Optional[Union[str, None]] = None , _lowerCamelCase :bool = False , _lowerCamelCase :Optional[str] = None , _lowerCamelCase :Optional[str] = None , _lowerCamelCase :Optional[str] = None , _lowerCamelCase :Optional["ort.SessionOptions"] = None , **_lowerCamelCase :Optional[int] , ): __SCREAMING_SNAKE_CASE : Any = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = OnnxRuntimeModel.load_model( os.path.join(_lowerCamelCase , _lowerCamelCase ) , provider=_lowerCamelCase , sess_options=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = Path(_lowerCamelCase ) # load model from hub else: # download model __SCREAMING_SNAKE_CASE : Optional[int] = hf_hub_download( repo_id=_lowerCamelCase , filename=_lowerCamelCase , use_auth_token=_lowerCamelCase , revision=_lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ).parent __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ).name __SCREAMING_SNAKE_CASE : List[Any] = OnnxRuntimeModel.load_model(_lowerCamelCase , provider=_lowerCamelCase , sess_options=_lowerCamelCase ) return cls(model=_lowerCamelCase , **_lowerCamelCase ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls :List[Any] , _lowerCamelCase :Union[str, Path] , _lowerCamelCase :bool = True , _lowerCamelCase :Optional[str] = None , _lowerCamelCase :Optional[str] = None , **_lowerCamelCase :List[str] , ): __SCREAMING_SNAKE_CASE : Optional[Any] = None if len(str(_lowerCamelCase ).split('''@''' ) ) == 2: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = model_id.split('''@''' ) return cls._from_pretrained( model_id=_lowerCamelCase , revision=_lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , use_auth_token=_lowerCamelCase , **_lowerCamelCase , )
674
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters _lowerCamelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Any , lowercase_ : str , lowercase_ : Optional[int]=None , lowercase_ : Dict=None ): '''simple docstring''' if "." in tensor_name: __SCREAMING_SNAKE_CASE : List[str] = tensor_name.split('''.''' ) for split in splits[:-1]: __SCREAMING_SNAKE_CASE : List[str] = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(F'''{module} has no attribute {split}.''' ) __SCREAMING_SNAKE_CASE : str = new_module __SCREAMING_SNAKE_CASE : Tuple = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F'''{module} does not have a parameter or a buffer named {tensor_name}.''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = tensor_name in module._buffers __SCREAMING_SNAKE_CASE : str = getattr(lowercase_ , lowercase_ ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(F'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.''' ) __SCREAMING_SNAKE_CASE : Optional[int] = False __SCREAMING_SNAKE_CASE : List[Any] = False if is_buffer or not is_bitsandbytes_available(): __SCREAMING_SNAKE_CASE : List[str] = False __SCREAMING_SNAKE_CASE : int = False else: __SCREAMING_SNAKE_CASE : Optional[Any] = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) __SCREAMING_SNAKE_CASE : Tuple = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: __SCREAMING_SNAKE_CASE : Dict = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: __SCREAMING_SNAKE_CASE : Any = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): __SCREAMING_SNAKE_CASE : str = value.to('''cpu''' ) if value.dtype == torch.inta: __SCREAMING_SNAKE_CASE : Union[str, Any] = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase_ , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None: __SCREAMING_SNAKE_CASE : Optional[Any] = new_value.T __SCREAMING_SNAKE_CASE : Optional[int] = old_value.__dict__ if is_abit: __SCREAMING_SNAKE_CASE : Union[str, Any] = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) elif is_abit: __SCREAMING_SNAKE_CASE : Union[str, Any] = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(lowercase_ ) ) else: if value is None: __SCREAMING_SNAKE_CASE : List[Any] = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): __SCREAMING_SNAKE_CASE : Union[str, Any] = value.to(lowercase_ ) else: __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase_ , device=lowercase_ ) if is_buffer: __SCREAMING_SNAKE_CASE : str = new_value else: __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad ) __SCREAMING_SNAKE_CASE : List[Any] = new_value def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple=None , lowercase_ : int=None , lowercase_ : Union[str, Any]=None , lowercase_ : List[str]=False ): '''simple docstring''' for name, module in model.named_children(): if current_key_name is None: __SCREAMING_SNAKE_CASE : int = [] current_key_name.append(lowercase_ ) if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(lowercase_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = module.weight.shape else: __SCREAMING_SNAKE_CASE : Optional[int] = module.in_features __SCREAMING_SNAKE_CASE : Union[str, Any] = module.out_features if quantization_config.quantization_method() == "llm_int8": __SCREAMING_SNAKE_CASE : Any = bnb.nn.LinearabitLt( lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) __SCREAMING_SNAKE_CASE : List[Any] = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: __SCREAMING_SNAKE_CASE : str = bnb.nn.Linearabit( lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) __SCREAMING_SNAKE_CASE : Any = True # Store the module class in case we need to transpose the weight later __SCREAMING_SNAKE_CASE : Dict = type(lowercase_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(lowercase_ ) if len(list(module.children() ) ) > 0: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : str=None , lowercase_ : Union[str, Any]=None , lowercase_ : Optional[int]=None ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def lowerCAmelCase_ ( *lowercase_ : Optional[Any] , **lowercase_ : Any ): '''simple docstring''' warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , lowercase_ , ) return replace_with_bnb_linear(*lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( *lowercase_ : Tuple , **lowercase_ : Any ): '''simple docstring''' warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , lowercase_ , ) return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() __SCREAMING_SNAKE_CASE : Union[str, Any] = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): __SCREAMING_SNAKE_CASE : str = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = sum(lowercase_ , [] ) __SCREAMING_SNAKE_CASE : List[str] = len(lowercase_ ) > 0 # Check if it is a base model __SCREAMING_SNAKE_CASE : str = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head __SCREAMING_SNAKE_CASE : Optional[int] = list(model.named_children() ) __SCREAMING_SNAKE_CASE : Optional[Any] = [list_modules[-1][0]] # add last module together with tied weights __SCREAMING_SNAKE_CASE : str = set(lowercase_ ) - set(lowercase_ ) __SCREAMING_SNAKE_CASE : List[Any] = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys __SCREAMING_SNAKE_CASE : Any = ['''.weight''', '''.bias'''] __SCREAMING_SNAKE_CASE : Any = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: __SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(lowercase_ , '''''' ) filtered_module_names.append(lowercase_ ) return filtered_module_names
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" import os from math import logaa def lowerCAmelCase_ ( lowercase_ : str = "base_exp.txt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : float = 0 __SCREAMING_SNAKE_CASE : List[str] = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(lowercase_ ) , lowercase_ ) ) ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = list(map(lowercase_ , line.split(''',''' ) ) ) if x * logaa(lowercase_ ) > largest: __SCREAMING_SNAKE_CASE : List[Any] = x * logaa(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = i + 1 return result if __name__ == "__main__": print(solution())
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :Dict , _lowerCamelCase :List[Any] , _lowerCamelCase :List[str]=7 , _lowerCamelCase :Optional[Any]=3 , _lowerCamelCase :Union[str, Any]=1_8 , _lowerCamelCase :int=3_0 , _lowerCamelCase :Union[str, Any]=4_0_0 , _lowerCamelCase :str=True , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :int=True , ): __SCREAMING_SNAKE_CASE : Any = size if size is not None else {'''height''': 1_8, '''width''': 1_8} __SCREAMING_SNAKE_CASE : List[Any] = parent __SCREAMING_SNAKE_CASE : List[Any] = batch_size __SCREAMING_SNAKE_CASE : int = num_channels __SCREAMING_SNAKE_CASE : Tuple = image_size __SCREAMING_SNAKE_CASE : Optional[int] = min_resolution __SCREAMING_SNAKE_CASE : str = max_resolution __SCREAMING_SNAKE_CASE : List[Any] = do_resize __SCREAMING_SNAKE_CASE : List[Any] = size __SCREAMING_SNAKE_CASE : List[Any] = apply_ocr def SCREAMING_SNAKE_CASE_ ( self :Dict ): return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = LayoutLMvaImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Any ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''apply_ocr''' ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 1_8, '''width''': 1_8} ) __SCREAMING_SNAKE_CASE : Any = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'''height''': 4_2, '''width''': 4_2} ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): pass def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : int = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , _lowerCamelCase ) self.assertIsInstance(encoding.boxes , _lowerCamelCase ) # Test batched __SCREAMING_SNAKE_CASE : int = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE_ ( self :str ): # Initialize image_processing __SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : List[str] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched __SCREAMING_SNAKE_CASE : Dict = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # with apply_OCR = True __SCREAMING_SNAKE_CASE : Any = LayoutLMvaImageProcessor() from datasets import load_dataset __SCREAMING_SNAKE_CASE : Union[str, Any] = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) __SCREAMING_SNAKE_CASE : Optional[int] = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __SCREAMING_SNAKE_CASE : Any = image_processing(_lowerCamelCase , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __SCREAMING_SNAKE_CASE : Union[str, Any] = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 __SCREAMING_SNAKE_CASE : Any = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , _lowerCamelCase ) self.assertListEqual(encoding.boxes , _lowerCamelCase ) # with apply_OCR = False __SCREAMING_SNAKE_CASE : Union[str, Any] = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1
"""simple docstring""" 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 snake_case ( nn.Module ): def __init__( self :Optional[Any] , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :Union[str, Any]=0.0 , _lowerCamelCase :Optional[int] = None , _lowerCamelCase :str = "geglu" , _lowerCamelCase :Optional[int] = None , _lowerCamelCase :bool = False , _lowerCamelCase :bool = False , _lowerCamelCase :bool = False , _lowerCamelCase :bool = False , _lowerCamelCase :bool = True , _lowerCamelCase :str = "layer_norm" , _lowerCamelCase :bool = False , ): super().__init__() __SCREAMING_SNAKE_CASE : Optional[Any] = only_cross_attention __SCREAMING_SNAKE_CASE : Union[str, Any] = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm_zero''' __SCREAMING_SNAKE_CASE : Optional[int] = (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: __SCREAMING_SNAKE_CASE : Union[str, Any] = AdaLayerNorm(_lowerCamelCase , _lowerCamelCase ) elif self.use_ada_layer_norm_zero: __SCREAMING_SNAKE_CASE : Any = AdaLayerNormZero(_lowerCamelCase , _lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : List[Any] = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = Attention( query_dim=_lowerCamelCase , heads=_lowerCamelCase , dim_head=_lowerCamelCase , dropout=_lowerCamelCase , bias=_lowerCamelCase , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=_lowerCamelCase , ) # 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. __SCREAMING_SNAKE_CASE : Union[str, Any] = ( AdaLayerNorm(_lowerCamelCase , _lowerCamelCase ) if self.use_ada_layer_norm else nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : int = Attention( query_dim=_lowerCamelCase , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=_lowerCamelCase , dim_head=_lowerCamelCase , dropout=_lowerCamelCase , bias=_lowerCamelCase , upcast_attention=_lowerCamelCase , ) # is self-attn if encoder_hidden_states is none else: __SCREAMING_SNAKE_CASE : Tuple = None __SCREAMING_SNAKE_CASE : List[str] = None # 3. Feed-forward __SCREAMING_SNAKE_CASE : Dict = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = FeedForward(_lowerCamelCase , dropout=_lowerCamelCase , activation_fn=_lowerCamelCase , final_dropout=_lowerCamelCase ) # let chunk size default to None __SCREAMING_SNAKE_CASE : Optional[Any] = None __SCREAMING_SNAKE_CASE : Optional[Any] = 0 def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Optional[int] , _lowerCamelCase :int ): # Sets chunk feed-forward __SCREAMING_SNAKE_CASE : Union[str, Any] = chunk_size __SCREAMING_SNAKE_CASE : Any = dim def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :Optional[torch.FloatTensor] = None , _lowerCamelCase :Optional[torch.FloatTensor] = None , _lowerCamelCase :Optional[torch.FloatTensor] = None , _lowerCamelCase :Optional[torch.LongTensor] = None , _lowerCamelCase :Dict[str, Any] = None , _lowerCamelCase :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: __SCREAMING_SNAKE_CASE : Optional[Any] = self.norma(_lowerCamelCase , _lowerCamelCase ) elif self.use_ada_layer_norm_zero: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.norma( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , hidden_dtype=hidden_states.dtype ) else: __SCREAMING_SNAKE_CASE : List[str] = self.norma(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = cross_attention_kwargs if cross_attention_kwargs is not None else {} __SCREAMING_SNAKE_CASE : Optional[int] = self.attna( _lowerCamelCase , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=_lowerCamelCase , **_lowerCamelCase , ) if self.use_ada_layer_norm_zero: __SCREAMING_SNAKE_CASE : List[Any] = gate_msa.unsqueeze(1 ) * attn_output __SCREAMING_SNAKE_CASE : Tuple = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: __SCREAMING_SNAKE_CASE : int = ( self.norma(_lowerCamelCase , _lowerCamelCase ) if self.use_ada_layer_norm else self.norma(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : int = self.attna( _lowerCamelCase , encoder_hidden_states=_lowerCamelCase , attention_mask=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[int] = attn_output + hidden_states # 3. Feed-forward __SCREAMING_SNAKE_CASE : str = self.norma(_lowerCamelCase ) if self.use_ada_layer_norm_zero: __SCREAMING_SNAKE_CASE : 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`.''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size __SCREAMING_SNAKE_CASE : str = torch.cat( [self.ff(_lowerCamelCase ) for hid_slice in norm_hidden_states.chunk(_lowerCamelCase , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: __SCREAMING_SNAKE_CASE : int = self.ff(_lowerCamelCase ) if self.use_ada_layer_norm_zero: __SCREAMING_SNAKE_CASE : Union[str, Any] = gate_mlp.unsqueeze(1 ) * ff_output __SCREAMING_SNAKE_CASE : Optional[int] = ff_output + hidden_states return hidden_states class snake_case ( nn.Module ): def __init__( self :Any , _lowerCamelCase :int , _lowerCamelCase :Optional[int] = None , _lowerCamelCase :int = 4 , _lowerCamelCase :float = 0.0 , _lowerCamelCase :str = "geglu" , _lowerCamelCase :bool = False , ): super().__init__() __SCREAMING_SNAKE_CASE : Optional[Any] = int(dim * mult ) __SCREAMING_SNAKE_CASE : Optional[int] = dim_out if dim_out is not None else dim if activation_fn == "gelu": __SCREAMING_SNAKE_CASE : Optional[Any] = GELU(_lowerCamelCase , _lowerCamelCase ) if activation_fn == "gelu-approximate": __SCREAMING_SNAKE_CASE : Tuple = GELU(_lowerCamelCase , _lowerCamelCase , approximate='''tanh''' ) elif activation_fn == "geglu": __SCREAMING_SNAKE_CASE : Tuple = GEGLU(_lowerCamelCase , _lowerCamelCase ) elif activation_fn == "geglu-approximate": __SCREAMING_SNAKE_CASE : Optional[Any] = ApproximateGELU(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = nn.ModuleList([] ) # project in self.net.append(_lowerCamelCase ) # project dropout self.net.append(nn.Dropout(_lowerCamelCase ) ) # project out self.net.append(nn.Linear(_lowerCamelCase , _lowerCamelCase ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :Dict ): for module in self.net: __SCREAMING_SNAKE_CASE : Any = module(_lowerCamelCase ) return hidden_states class snake_case ( nn.Module ): def __init__( self :Any , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :str = "none" ): super().__init__() __SCREAMING_SNAKE_CASE : int = nn.Linear(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = approximate def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :List[str] ): if gate.device.type != "mps": return F.gelu(_lowerCamelCase , 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 SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.proj(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = self.gelu(_lowerCamelCase ) return hidden_states class snake_case ( nn.Module ): def __init__( self :Any , _lowerCamelCase :int , _lowerCamelCase :int ): super().__init__() __SCREAMING_SNAKE_CASE : Any = nn.Linear(_lowerCamelCase , dim_out * 2 ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str ): if gate.device.type != "mps": return F.gelu(_lowerCamelCase ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.proj(_lowerCamelCase ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(_lowerCamelCase ) class snake_case ( nn.Module ): def __init__( self :Any , _lowerCamelCase :int , _lowerCamelCase :int ): super().__init__() __SCREAMING_SNAKE_CASE : str = nn.Linear(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = self.proj(_lowerCamelCase ) return x * torch.sigmoid(1.7_0_2 * x ) class snake_case ( nn.Module ): def __init__( self :str , _lowerCamelCase :Optional[int] , _lowerCamelCase :str ): super().__init__() __SCREAMING_SNAKE_CASE : str = nn.Embedding(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = nn.SiLU() __SCREAMING_SNAKE_CASE : Tuple = nn.Linear(_lowerCamelCase , embedding_dim * 2 ) __SCREAMING_SNAKE_CASE : Tuple = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = self.linear(self.silu(self.emb(_lowerCamelCase ) ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = torch.chunk(_lowerCamelCase , 2 ) __SCREAMING_SNAKE_CASE : List[str] = self.norm(_lowerCamelCase ) * (1 + scale) + shift return x class snake_case ( nn.Module ): def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :List[str] ): super().__init__() __SCREAMING_SNAKE_CASE : List[Any] = CombinedTimestepLabelEmbeddings(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = nn.SiLU() __SCREAMING_SNAKE_CASE : Any = nn.Linear(_lowerCamelCase , 6 * embedding_dim , bias=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase , eps=1e-6 ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :str , _lowerCamelCase :List[str] , _lowerCamelCase :Dict , _lowerCamelCase :Dict=None ): __SCREAMING_SNAKE_CASE : Tuple = self.linear(self.silu(self.emb(_lowerCamelCase , _lowerCamelCase , hidden_dtype=_lowerCamelCase ) ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = emb.chunk(6 , dim=1 ) __SCREAMING_SNAKE_CASE : int = self.norm(_lowerCamelCase ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class snake_case ( nn.Module ): def __init__( self :List[Any] , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :Optional[str] = None , _lowerCamelCase :float = 1e-5 ): super().__init__() __SCREAMING_SNAKE_CASE : int = num_groups __SCREAMING_SNAKE_CASE : List[str] = eps if act_fn is None: __SCREAMING_SNAKE_CASE : Tuple = None else: __SCREAMING_SNAKE_CASE : int = get_activation(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = nn.Linear(_lowerCamelCase , out_dim * 2 ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Dict , _lowerCamelCase :Any ): if self.act: __SCREAMING_SNAKE_CASE : int = self.act(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.linear(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = emb[:, :, None, None] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = emb.chunk(2 , dim=1 ) __SCREAMING_SNAKE_CASE : Tuple = F.group_norm(_lowerCamelCase , self.num_groups , eps=self.eps ) __SCREAMING_SNAKE_CASE : Optional[Any] = x * (1 + scale) + shift return x
674
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _lowerCamelCase = { '''configuration_ctrl''': ['''CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CTRLConfig'''], '''tokenization_ctrl''': ['''CTRLTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CTRLForSequenceClassification''', '''CTRLLMHeadModel''', '''CTRLModel''', '''CTRLPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFCTRLForSequenceClassification''', '''TFCTRLLMHeadModel''', '''TFCTRLModel''', '''TFCTRLPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig from .tokenization_ctrl import CTRLTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ctrl import ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, CTRLPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_ctrl import ( TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, TFCTRLForSequenceClassification, TFCTRLLMHeadModel, TFCTRLModel, TFCTRLPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
1
"""simple docstring""" # DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = 42 lowerCamelCase__ = 42 class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): lowerCamelCase__ = 1 @register_to_config def __init__( self :Optional[int] , _lowerCamelCase :int = 2_0_0_0 , _lowerCamelCase :float = 0.1_5 , _lowerCamelCase :float = 0.0_1 , _lowerCamelCase :float = 1_3_4_8.0 , _lowerCamelCase :float = 1e-5 , _lowerCamelCase :int = 1 , ): # standard deviation of the initial noise distribution __SCREAMING_SNAKE_CASE : List[Any] = sigma_max # setable values __SCREAMING_SNAKE_CASE : Union[str, Any] = None self.set_sigmas(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :Optional[int] = None ): return sample def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :int , _lowerCamelCase :float = None , _lowerCamelCase :Union[str, torch.device] = None ): __SCREAMING_SNAKE_CASE : Optional[int] = sampling_eps if sampling_eps is not None else self.config.sampling_eps __SCREAMING_SNAKE_CASE : List[Any] = torch.linspace(1 , _lowerCamelCase , _lowerCamelCase , device=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :int , _lowerCamelCase :float = None , _lowerCamelCase :float = None , _lowerCamelCase :float = None ): __SCREAMING_SNAKE_CASE : Optional[int] = sigma_min if sigma_min is not None else self.config.sigma_min __SCREAMING_SNAKE_CASE : List[Any] = sigma_max if sigma_max is not None else self.config.sigma_max __SCREAMING_SNAKE_CASE : Dict = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) __SCREAMING_SNAKE_CASE : Dict = torch.exp(torch.linspace(math.log(_lowerCamelCase ) , math.log(_lowerCamelCase ) , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : int = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Tuple , _lowerCamelCase :int ): return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :int , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :Optional[torch.Generator] = None , _lowerCamelCase :bool = True , ): if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) __SCREAMING_SNAKE_CASE : str = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) __SCREAMING_SNAKE_CASE : str = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda __SCREAMING_SNAKE_CASE : List[str] = timesteps.to(self.discrete_sigmas.device ) __SCREAMING_SNAKE_CASE : Any = self.discrete_sigmas[timesteps].to(sample.device ) __SCREAMING_SNAKE_CASE : int = self.get_adjacent_sigma(_lowerCamelCase , _lowerCamelCase ).to(sample.device ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.zeros_like(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods __SCREAMING_SNAKE_CASE : List[str] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): __SCREAMING_SNAKE_CASE : Optional[int] = diffusion.unsqueeze(-1 ) __SCREAMING_SNAKE_CASE : int = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of __SCREAMING_SNAKE_CASE : str = randn_tensor( sample.shape , layout=sample.layout , generator=_lowerCamelCase , device=sample.device , dtype=sample.dtype ) __SCREAMING_SNAKE_CASE : Any = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? __SCREAMING_SNAKE_CASE : Optional[Any] = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=_lowerCamelCase , prev_sample_mean=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :Optional[torch.Generator] = None , _lowerCamelCase :bool = True , ): if self.timesteps is None: raise ValueError( '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler''' ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction __SCREAMING_SNAKE_CASE : Tuple = randn_tensor(sample.shape , layout=sample.layout , generator=_lowerCamelCase ).to(sample.device ) # compute step size from the model_output, the noise, and the snr __SCREAMING_SNAKE_CASE : Optional[Any] = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() __SCREAMING_SNAKE_CASE : Dict = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() __SCREAMING_SNAKE_CASE : Dict = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 __SCREAMING_SNAKE_CASE : Tuple = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term __SCREAMING_SNAKE_CASE : Any = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): __SCREAMING_SNAKE_CASE : List[str] = step_size.unsqueeze(-1 ) __SCREAMING_SNAKE_CASE : int = sample + step_size * model_output __SCREAMING_SNAKE_CASE : Union[str, Any] = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :torch.FloatTensor , _lowerCamelCase :torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples __SCREAMING_SNAKE_CASE : Optional[Any] = timesteps.to(original_samples.device ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.discrete_sigmas.to(original_samples.device )[timesteps] __SCREAMING_SNAKE_CASE : Tuple = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(_lowerCamelCase ) * sigmas[:, None, None, None] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = noise + original_samples return noisy_samples def __len__( self :List[Any] ): return self.config.num_train_timesteps
674
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
1
"""simple docstring""" from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = TypeVar('''DatasetType''', Dataset, IterableDataset) def lowerCAmelCase_ ( lowercase_ : List[DatasetType] , lowercase_ : Optional[List[float]] = None , lowercase_ : Optional[int] = None , lowercase_ : Optional[DatasetInfo] = None , lowercase_ : Optional[NamedSplit] = None , lowercase_ : Literal["first_exhausted", "all_exhausted"] = "first_exhausted" , ): '''simple docstring''' from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError('''Unable to interleave an empty list of datasets.''' ) for i, dataset in enumerate(lowercase_ ): if not isinstance(lowercase_ , (Dataset, IterableDataset) ): if isinstance(lowercase_ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ''' '''is an empty dataset dictionary.''' ) raise ValueError( F'''Dataset at position {i} has at least one split: {list(lowercase_ )}\n''' F'''Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(lowercase_ ) )}\']''' ) raise ValueError( F'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowercase_ ).__name__}.''' ) if i == 0: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = ( (Dataset, IterableDataset) if isinstance(lowercase_ , lowercase_ ) else (IterableDataset, Dataset) ) elif not isinstance(lowercase_ , lowercase_ ): raise ValueError( F'''Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.''' ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(F'''{stopping_strategy} is not supported. Please enter a valid stopping_strategy.''' ) if dataset_type is Dataset: return _interleave_map_style_datasets( lowercase_ , lowercase_ , lowercase_ , info=lowercase_ , split=lowercase_ , stopping_strategy=lowercase_ ) else: return _interleave_iterable_datasets( lowercase_ , lowercase_ , lowercase_ , info=lowercase_ , split=lowercase_ , stopping_strategy=lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[DatasetType] , lowercase_ : Optional[DatasetInfo] = None , lowercase_ : Optional[NamedSplit] = None , lowercase_ : int = 0 , ): '''simple docstring''' if not dsets: raise ValueError('''Unable to concatenate an empty list of datasets.''' ) for i, dataset in enumerate(lowercase_ ): if not isinstance(lowercase_ , (Dataset, IterableDataset) ): if isinstance(lowercase_ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ''' '''is an empty dataset dictionary.''' ) raise ValueError( F'''Dataset at position {i} has at least one split: {list(lowercase_ )}\n''' F'''Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(lowercase_ ) )}\']''' ) raise ValueError( F'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowercase_ ).__name__}.''' ) if i == 0: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = ( (Dataset, IterableDataset) if isinstance(lowercase_ , lowercase_ ) else (IterableDataset, Dataset) ) elif not isinstance(lowercase_ , lowercase_ ): raise ValueError( F'''Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.''' ) if dataset_type is Dataset: return _concatenate_map_style_datasets(lowercase_ , info=lowercase_ , split=lowercase_ , axis=lowercase_ ) else: return _concatenate_iterable_datasets(lowercase_ , info=lowercase_ , split=lowercase_ , axis=lowercase_ )
674
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = {'''configuration_xlnet''': ['''XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLNetConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['''XLNetTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['''XLNetTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLNetForMultipleChoice''', '''XLNetForQuestionAnswering''', '''XLNetForQuestionAnsweringSimple''', '''XLNetForSequenceClassification''', '''XLNetForTokenClassification''', '''XLNetLMHeadModel''', '''XLNetModel''', '''XLNetPreTrainedModel''', '''load_tf_weights_in_xlnet''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLNetForMultipleChoice''', '''TFXLNetForQuestionAnsweringSimple''', '''TFXLNetForSequenceClassification''', '''TFXLNetForTokenClassification''', '''TFXLNetLMHeadModel''', '''TFXLNetMainLayer''', '''TFXLNetModel''', '''TFXLNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
1
"""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 _lowerCamelCase = '''bart''' _lowerCamelCase = True @st.cache(allow_output_mutation=lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' if LOAD_DENSE_INDEX: __SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained('''yjernite/retribert-base-uncased''' ) __SCREAMING_SNAKE_CASE : List[str] = AutoModel.from_pretrained('''yjernite/retribert-base-uncased''' ).to('''cuda:0''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = qar_model.eval() else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = (None, None) if MODEL_TYPE == "bart": __SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained('''yjernite/bart_eli5''' ) __SCREAMING_SNAKE_CASE : str = AutoModelForSeqaSeqLM.from_pretrained('''yjernite/bart_eli5''' ).to('''cuda:0''' ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.load('''seq2seq_models/eli5_bart_model_blm_2.pth''' ) sas_model.load_state_dict(save_dict['''model'''] ) __SCREAMING_SNAKE_CASE : List[Any] = sas_model.eval() else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : 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=lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' if LOAD_DENSE_INDEX: __SCREAMING_SNAKE_CASE : Union[str, Any] = faiss.StandardGpuResources() __SCREAMING_SNAKE_CASE : Dict = datasets.load_dataset(path='''wiki_snippets''' , name='''wiki40b_en_100_0''' )['''train'''] __SCREAMING_SNAKE_CASE : Dict = np.memmap( '''wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat''' , dtype='''float32''' , mode='''r''' , shape=(wikiaab_passages.num_rows, 128) , ) __SCREAMING_SNAKE_CASE : Tuple = faiss.IndexFlatIP(128 ) __SCREAMING_SNAKE_CASE : List[str] = faiss.index_cpu_to_gpu(lowercase_ , 1 , lowercase_ ) wikiaab_gpu_index_flat.add(lowercase_ ) # TODO fix for larger GPU else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = (None, None) __SCREAMING_SNAKE_CASE : Union[str, Any] = Elasticsearch([{'''host''': '''localhost''', '''port''': '''9200'''}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = datasets.load_dataset('''eli5''' , name='''LFQA_reddit''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = elia['''train_eli5'''] __SCREAMING_SNAKE_CASE : List[str] = np.memmap( '''eli5_questions_reps.dat''' , dtype='''float32''' , mode='''r''' , shape=(elia_train.num_rows, 128) ) __SCREAMING_SNAKE_CASE : int = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(lowercase_ ) return (elia_train, eli5_train_q_index) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = load_indexes() _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = load_models() _lowerCamelCase , _lowerCamelCase = load_train_data() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Optional[Any]=10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = embed_questions_for_retrieval([question] , lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = eli5_train_q_index.search(lowercase_ , lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = [elia_train[int(lowercase_ )] for i in I[0]] return nn_examples def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : List[str]="wiki40b" , lowercase_ : Optional[Any]="dense" , lowercase_ : Tuple=10 ): '''simple docstring''' if source == "none": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = (''' <P> '''.join(['''''' for _ in range(11 )] ).strip(), []) else: if method == "dense": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = query_qa_dense_index( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = query_es_index( lowercase_ , lowercase_ , index_name='''english_wiki40b_snippets_100w''' , n_results=lowercase_ , ) __SCREAMING_SNAKE_CASE : Optional[Any] = [ (res['''article_title'''], res['''section_title'''].strip(), res['''score'''], res['''passage_text''']) for res in hit_lst ] __SCREAMING_SNAKE_CASE : Dict = '''question: {} context: {}'''.format(lowercase_ , lowercase_ ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda lowercase_ : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda lowercase_ : None), } ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : str , lowercase_ : Optional[int] , lowercase_ : Optional[int]=64 , lowercase_ : List[Any]=256 , lowercase_ : str=False , lowercase_ : str=2 , lowercase_ : List[str]=0.95 , lowercase_ : Union[str, Any]=0.8 ): '''simple docstring''' with torch.no_grad(): __SCREAMING_SNAKE_CASE : Dict = qa_sas_generate( lowercase_ , lowercase_ , lowercase_ , num_answers=1 , num_beams=lowercase_ , min_len=lowercase_ , max_len=lowercase_ , do_sample=lowercase_ , temp=lowercase_ , top_p=lowercase_ , top_k=lowercase_ , max_input_length=1024 , device='''cuda:0''' , )[0] return (answer, support_list) st.title('''Long Form Question Answering with ELI5''') # Start sidebar _lowerCamelCase = '''<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>''' _lowerCamelCase = ''' <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 _lowerCamelCase = ''' 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) _lowerCamelCase = [ '''Answer the question''', '''View the retrieved document only''', '''View the most similar ELI5 question and answer''', '''Show me everything, please!''', ] _lowerCamelCase = st.sidebar.checkbox('''Demo options''') if demo_options: _lowerCamelCase = st.sidebar.selectbox( '''''', action_list, index=3, ) _lowerCamelCase = action_list.index(action_st) _lowerCamelCase = st.sidebar.selectbox( '''''', ['''Show full text of passages''', '''Show passage section titles'''], index=0, ) _lowerCamelCase = show_type == '''Show full text of passages''' else: _lowerCamelCase = 3 _lowerCamelCase = True _lowerCamelCase = st.sidebar.checkbox('''Retrieval options''') if retrieval_options: _lowerCamelCase = ''' ### 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) _lowerCamelCase = st.sidebar.selectbox('''Which Wikipedia format should the model use?''', ['''wiki40b''', '''none''']) _lowerCamelCase = st.sidebar.selectbox('''Which Wikipedia indexer should the model use?''', ['''dense''', '''sparse''', '''mixed''']) else: _lowerCamelCase = '''wiki40b''' _lowerCamelCase = '''dense''' _lowerCamelCase = '''beam''' _lowerCamelCase = 2 _lowerCamelCase = 64 _lowerCamelCase = 2_56 _lowerCamelCase = None _lowerCamelCase = None _lowerCamelCase = st.sidebar.checkbox('''Generation options''') if generate_options: _lowerCamelCase = ''' ### 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) _lowerCamelCase = st.sidebar.selectbox('''Would you like to use beam search or sample an answer?''', ['''beam''', '''sampled''']) _lowerCamelCase = st.sidebar.slider( '''Minimum generation length''', min_value=8, max_value=2_56, value=64, step=8, format=None, key=None ) _lowerCamelCase = st.sidebar.slider( '''Maximum generation length''', min_value=64, max_value=5_12, value=2_56, step=16, format=None, key=None ) if sampled == "beam": _lowerCamelCase = st.sidebar.slider('''Beam size''', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: _lowerCamelCase = st.sidebar.slider( '''Nucleus sampling p''', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) _lowerCamelCase = st.sidebar.slider( '''Temperature''', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) _lowerCamelCase = None # start main text _lowerCamelCase = [ '''<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?''', ] _lowerCamelCase = 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>": _lowerCamelCase = st.text_input('''Enter your question here:''', '''''') else: _lowerCamelCase = question_s if st.button('''Show me!'''): if action in [0, 1, 3]: if index_type == "mixed": _lowerCamelCase , _lowerCamelCase = make_support(question, source=wiki_source, method='''dense''', n_results=10) _lowerCamelCase , _lowerCamelCase = make_support(question, source=wiki_source, method='''sparse''', n_results=10) _lowerCamelCase = [] 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)] _lowerCamelCase = support_list[:10] _lowerCamelCase = '''<P> ''' + ''' <P> '''.join([res[-1] for res in support_list]) else: _lowerCamelCase , _lowerCamelCase = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: _lowerCamelCase , _lowerCamelCase = 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): _lowerCamelCase = '''https://en.wikipedia.org/wiki/{}'''.format(res[0].replace(''' ''', '''_''')) _lowerCamelCase = res[1].strip() if sec_titles == "": _lowerCamelCase = '''[{}]({})'''.format(res[0], wiki_url) else: _lowerCamelCase = sec_titles.split(''' & ''') _lowerCamelCase = ''' & '''.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]: _lowerCamelCase = find_nearest_training(question) _lowerCamelCase = nn_train_list[0] st.markdown( '''--- \n ### The most similar question in the ELI5 training set was: \n\n {}'''.format(train_exple['''title''']) ) _lowerCamelCase = [ '''{}. {}'''.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))) _lowerCamelCase = ''' --- **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)
674
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : int = 10**12 ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = 1 __SCREAMING_SNAKE_CASE : Optional[int] = 0 __SCREAMING_SNAKE_CASE : str = 1 __SCREAMING_SNAKE_CASE : Any = 1 while numerator <= 2 * min_total - 1: prev_numerator += 2 * numerator numerator += 2 * prev_numerator prev_denominator += 2 * denominator denominator += 2 * prev_denominator return (denominator + 1) // 2 if __name__ == "__main__": print(f'{solution() = }')
674
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __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 : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''timm_backbone''' def __init__( self :int , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=3 , _lowerCamelCase :int=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Tuple=None , **_lowerCamelCase :Any , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = backbone __SCREAMING_SNAKE_CASE : Dict = num_channels __SCREAMING_SNAKE_CASE : Optional[Any] = features_only __SCREAMING_SNAKE_CASE : Optional[Any] = use_pretrained_backbone __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Tuple = out_indices if out_indices is not None else (-1,)
674
"""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 _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): 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 SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): 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 SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
1
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class snake_case : lowerCamelCase__ = 42 lowerCamelCase__ = None lowerCamelCase__ = None def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Node(1 ) __SCREAMING_SNAKE_CASE : str = Node(2 ) __SCREAMING_SNAKE_CASE : int = Node(3 ) __SCREAMING_SNAKE_CASE : Optional[Any] = Node(4 ) __SCREAMING_SNAKE_CASE : int = Node(5 ) return tree def lowerCAmelCase_ ( lowercase_ : Node | None ): '''simple docstring''' return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def lowerCAmelCase_ ( lowercase_ : Node | None ): '''simple docstring''' return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def lowerCAmelCase_ ( lowercase_ : Node | None ): '''simple docstring''' return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def lowerCAmelCase_ ( lowercase_ : Node | None ): '''simple docstring''' return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def lowerCAmelCase_ ( lowercase_ : Node | None ): '''simple docstring''' __SCREAMING_SNAKE_CASE : list[Any] = [] if root is None: return output __SCREAMING_SNAKE_CASE : Tuple = deque([root] ) while process_queue: __SCREAMING_SNAKE_CASE : Optional[Any] = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def lowerCAmelCase_ ( lowercase_ : Node | None , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : list[Any] = [] def populate_output(lowercase_ : Node | None , lowercase_ : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(lowercase_ , lowercase_ ) return output def lowerCAmelCase_ ( lowercase_ : Node | None , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : list[Any] = [] def populate_output(lowercase_ : Node | None , lowercase_ : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(lowercase_ , lowercase_ ) return output def lowerCAmelCase_ ( lowercase_ : Node | None ): '''simple docstring''' if root is None: return [] __SCREAMING_SNAKE_CASE : list[Sequence[Node | None]] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : List[str] = height(lowercase_ ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(lowercase_ , lowercase_ ) ) __SCREAMING_SNAKE_CASE : int = 1 else: output.append(get_nodes_from_right_to_left(lowercase_ , lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = 0 return output def lowerCAmelCase_ ( ): # Main function for testing. '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = make_tree() print(F'''In-order Traversal: {inorder(lowercase_ )}''' ) print(F'''Pre-order Traversal: {preorder(lowercase_ )}''' ) print(F'''Post-order Traversal: {postorder(lowercase_ )}''' , '''\n''' ) print(F'''Height of Tree: {height(lowercase_ )}''' , '''\n''' ) print('''Complete Level Order Traversal: ''' ) print(level_order(lowercase_ ) , '''\n''' ) print('''Level-wise order Traversal: ''' ) for level in range(1 , height(lowercase_ ) + 1 ): print(F'''Level {level}:''' , get_nodes_from_left_to_right(lowercase_ , level=lowercase_ ) ) print('''\nZigZag order Traversal: ''' ) print(zigzag(lowercase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
674
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = { '''configuration_roformer''': ['''ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RoFormerConfig''', '''RoFormerOnnxConfig'''], '''tokenization_roformer''': ['''RoFormerTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['''RoFormerTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RoFormerForCausalLM''', '''RoFormerForMaskedLM''', '''RoFormerForMultipleChoice''', '''RoFormerForQuestionAnswering''', '''RoFormerForSequenceClassification''', '''RoFormerForTokenClassification''', '''RoFormerLayer''', '''RoFormerModel''', '''RoFormerPreTrainedModel''', '''load_tf_weights_in_roformer''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRoFormerForCausalLM''', '''TFRoFormerForMaskedLM''', '''TFRoFormerForMultipleChoice''', '''TFRoFormerForQuestionAnswering''', '''TFRoFormerForSequenceClassification''', '''TFRoFormerForTokenClassification''', '''TFRoFormerLayer''', '''TFRoFormerModel''', '''TFRoFormerPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxRoFormerForMaskedLM''', '''FlaxRoFormerForMultipleChoice''', '''FlaxRoFormerForQuestionAnswering''', '''FlaxRoFormerForSequenceClassification''', '''FlaxRoFormerForTokenClassification''', '''FlaxRoFormerModel''', '''FlaxRoFormerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
1
"""simple docstring""" import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = DDIMPipeline lowerCamelCase__ = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowerCamelCase__ = PipelineTesterMixin.required_optional_params - { '''num_images_per_prompt''', '''latents''', '''callback''', '''callback_steps''', } lowerCamelCase__ = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :List[str] ): torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) __SCREAMING_SNAKE_CASE : List[Any] = DDIMScheduler() __SCREAMING_SNAKE_CASE : Optional[int] = {'''unet''': unet, '''scheduler''': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[int]=0 ): if str(_lowerCamelCase ).startswith('''mps''' ): __SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : List[str] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = '''cpu''' __SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_components() __SCREAMING_SNAKE_CASE : int = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_inputs(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = pipe(**_lowerCamelCase ).images __SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 3_2, 3_2, 3) ) __SCREAMING_SNAKE_CASE : Any = np.array( [1.0_00e00, 5.7_17e-01, 4.7_17e-01, 1.0_00e00, 0.0_00e00, 1.0_00e00, 3.0_00e-04, 0.0_00e00, 9.0_00e-04] ) __SCREAMING_SNAKE_CASE : Any = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = '''google/ddpm-cifar10-32''' __SCREAMING_SNAKE_CASE : Any = UNetaDModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = DDIMScheduler() __SCREAMING_SNAKE_CASE : Dict = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddim.to(_lowerCamelCase ) ddim.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : str = ddim(generator=_lowerCamelCase , eta=0.0 , output_type='''numpy''' ).images __SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE : int = np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : List[str] = '''google/ddpm-ema-bedroom-256''' __SCREAMING_SNAKE_CASE : str = UNetaDModel.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = DDIMScheduler.from_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddpm.to(_lowerCamelCase ) ddpm.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Optional[int] = ddpm(generator=_lowerCamelCase , output_type='''numpy''' ).images __SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 2_5_6, 2_5_6, 3) __SCREAMING_SNAKE_CASE : List[Any] = np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
674
"""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 snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # 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(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) 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 SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = 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. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''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]
674
1
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
1
"""simple docstring""" import logging from transformers import PretrainedConfig _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = { '''bertabs-finetuned-cnndm''': '''https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''bertabs''' def __init__( self :Dict , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :Tuple=5_1_2 , _lowerCamelCase :Optional[int]=6 , _lowerCamelCase :str=5_1_2 , _lowerCamelCase :List[Any]=8 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[Any]=0.2 , _lowerCamelCase :int=6 , _lowerCamelCase :List[Any]=7_6_8 , _lowerCamelCase :Dict=8 , _lowerCamelCase :Union[str, Any]=2_0_4_8 , _lowerCamelCase :List[Any]=0.2 , **_lowerCamelCase :str , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[Any] = max_pos __SCREAMING_SNAKE_CASE : Union[str, Any] = enc_layers __SCREAMING_SNAKE_CASE : Dict = enc_hidden_size __SCREAMING_SNAKE_CASE : List[str] = enc_heads __SCREAMING_SNAKE_CASE : Tuple = enc_ff_size __SCREAMING_SNAKE_CASE : Union[str, Any] = enc_dropout __SCREAMING_SNAKE_CASE : Union[str, Any] = dec_layers __SCREAMING_SNAKE_CASE : str = dec_hidden_size __SCREAMING_SNAKE_CASE : Dict = dec_heads __SCREAMING_SNAKE_CASE : Optional[int] = dec_ff_size __SCREAMING_SNAKE_CASE : List[str] = dec_dropout
674
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
1
"""simple docstring""" import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class snake_case ( unittest.TestCase ): lowerCamelCase__ = JukeboxTokenizer lowerCamelCase__ = { '''artist''': '''Zac Brown Band''', '''genres''': '''Country''', '''lyrics''': '''I met a traveller from an antique land, Who said "Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away ''', } @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): import torch __SCREAMING_SNAKE_CASE : Union[str, Any] = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) __SCREAMING_SNAKE_CASE : int = tokenizer(**self.metas )['''input_ids'''] # fmt: off __SCREAMING_SNAKE_CASE : str = [ torch.tensor([[ 0, 0, 0, 7_1_6_9, 5_0_7, 9, 7_6, 3_9, 3_1, 4_6, 7_6, 2_7, 7_6, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_6, 3_2, 4_4, 4_1, 3_9, 7_6, 2_7, 4_0, 7_6, 2_7, 4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_6, 3_8, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 4_1, 7_6, 4_5, 2_7, 3_5, 3_0, 7_6, 7_1, 2_0, 4_9, 4_1, 7_6, 4_8, 2_7, 4_5, 4_6, 7_6, 2_7, 4_0, 3_0, 7_6, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5, 4_5, 7_6, 3_8, 3_1, 3_3, 4_5, 7_6, 4_1, 3_2, 7_6, 4_5, 4_6, 4_1, 4_0, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_9, 4_6, 2_7, 4_0, 3_0, 7_6, 3_5, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_6, 6_3, 7_6, 6_3, 7_6, 6_3, 7_6, 1_4, 3_1, 2_7, 4_4, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_5, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 8, 2_7, 3_8, 3_2, 7_6, 4_5, 4_7, 4_0, 3_7, 7_6, 2_7, 7_6, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_6, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_6, 3_8, 3_5, 3_1, 4_5, 6_4, 7_6, 4_9, 3_4, 4_1, 4_5, 3_1, 7_6, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_6, 3_8, 3_5, 4_2, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 4_5, 4_0, 3_1, 3_1, 4_4, 7_6, 4_1, 3_2, 7_6, 2_9, 4_1, 3_8, 3_0, 7_6, 2_9, 4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_5, 4_6, 4_5, 7_6, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_6, 4_9, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 4_1, 4_5, 3_1, 7_6, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_6, 4_4, 3_1, 2_7, 3_0, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 3_5, 2_9, 3_4, 7_6, 5_1, 3_1, 4_6, 7_6, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_6, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_6, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1, 7_6, 3_4, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_4, 3_1, 2_7, 4_4, 4_6, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_2, 3_1, 3_0, 6_6, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_2, 3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 4_9, 4_1, 4_4, 3_0, 4_5, 7_6, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_3, 5_1, 7_6, 4_0, 2_7, 3_9, 3_1, 7_6, 3_5, 4_5, 7_6, 1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_6, 1_1, 3_5, 4_0, 3_3, 7_6, 4_1, 3_2, 7_6, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_2, 4_1, 4_1, 3_7, 7_6, 4_1, 4_0, 7_6, 3_9, 5_1, 7_6, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4, 7_6, 5_1, 3_1, 7_6, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_6, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_6, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_6, 1_8, 4_1, 4_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 2_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_5, 3_2, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7, 3_8, 7_6, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_6, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_6, 2_7, 4_0, 3_0, 7_6, 2_8, 2_7, 4_4, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1, 7_6, 3_8, 4_1, 4_0, 3_1, 7_6, 2_7, 4_0, 3_0, 7_6, 3_8, 3_1, 4_8, 3_1, 3_8, 7_6, 4_5, 2_7, 4_0, 3_0, 4_5, 7_6, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_6, 3_2, 2_7, 4_4, 7_6, 2_7, 4_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): import torch __SCREAMING_SNAKE_CASE : Tuple = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) __SCREAMING_SNAKE_CASE : Tuple = tokenizer(**self.metas )['''input_ids'''] # fmt: off __SCREAMING_SNAKE_CASE : Union[str, Any] = [ torch.tensor([[ 0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1, 9, 7_7, 3_9, 3_1, 4_6, 7_7, 2_7, 7_7, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_7, 3_2, 4_4, 4_1, 3_9, 7_7, 2_7, 4_0, 7_7, 2_7, 4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_7, 3_8, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 4_1, 7_7, 4_5, 2_7, 3_5, 3_0, 7_7, 7_2, 2_0, 4_9, 4_1, 7_7, 4_8, 2_7, 4_5, 4_6, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5, 4_5, 7_7, 3_8, 3_1, 3_3, 4_5, 7_7, 4_1, 3_2, 7_7, 4_5, 4_6, 4_1, 4_0, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_9, 4_6, 2_7, 4_0, 3_0, 7_7, 3_5, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 1_4, 3_1, 2_7, 4_4, 7_7, 4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_5, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 8, 2_7, 3_8, 3_2, 7_7, 4_5, 4_7, 4_0, 3_7, 7_7, 2_7, 7_7, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_7, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_7, 3_8, 3_5, 3_1, 4_5, 6_4, 7_7, 4_9, 3_4, 4_1, 4_5, 3_1, 7_7, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1, 4_0, 3_0, 7_7, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_7, 3_8, 3_5, 4_2, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_5, 4_0, 3_1, 3_1, 4_4, 7_7, 4_1, 3_2, 7_7, 2_9, 4_1, 3_8, 3_0, 7_7, 2_9, 4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_5, 4_6, 4_5, 7_7, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_7, 4_9, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 4_1, 4_5, 3_1, 7_7, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_7, 4_4, 3_1, 2_7, 3_0, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 3_5, 2_9, 3_4, 7_7, 5_1, 3_1, 4_6, 7_7, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_7, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7, 3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_7, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_4, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_7, 4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_4, 3_1, 2_7, 4_4, 4_6, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_2, 3_1, 3_0, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1, 4_0, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_2, 3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7, 4_9, 4_1, 4_4, 3_0, 4_5, 7_7, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_3, 5_1, 7_7, 4_0, 2_7, 3_9, 3_1, 7_7, 3_5, 4_5, 7_7, 1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_7, 1_1, 3_5, 4_0, 3_3, 7_7, 4_1, 3_2, 7_7, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_2, 4_1, 4_1, 3_7, 7_7, 4_1, 4_0, 7_7, 3_9, 5_1, 7_7, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4, 7_7, 5_1, 3_1, 7_7, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_7, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_7, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_7, 1_8, 4_1, 4_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 2_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_5, 3_2, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7, 3_8, 7_7, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_7, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_7, 2_7, 4_0, 3_0, 7_7, 2_8, 2_7, 4_4, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_8, 4_1, 4_0, 3_1, 7_7, 2_7, 4_0, 3_0, 7_7, 3_8, 3_1, 4_8, 3_1, 3_8, 7_7, 4_5, 2_7, 4_0, 3_0, 4_5, 7_7, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_7, 3_2, 2_7, 4_4, 7_7, 2_7, 4_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
674
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
1
"""simple docstring""" def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return "".join(chr(ord(lowercase_ ) - 32 ) if '''a''' <= char <= '''z''' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
674
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL _lowerCamelCase = logging.get_logger(__name__) def lowerCAmelCase_ ( lowercase_ : np.ndarray , lowercase_ : Union[int, Iterable[int]] , lowercase_ : bool , lowercase_ : int ): '''simple docstring''' def constraint_to_multiple_of(lowercase_ : int , lowercase_ : str , lowercase_ : Any=0 , lowercase_ : Any=None ): __SCREAMING_SNAKE_CASE : Tuple = round(val / multiple ) * multiple if max_val is not None and x > max_val: __SCREAMING_SNAKE_CASE : List[Any] = math.floor(val / multiple ) * multiple if x < min_val: __SCREAMING_SNAKE_CASE : List[Any] = math.ceil(val / multiple ) * multiple return x __SCREAMING_SNAKE_CASE : str = (output_size, output_size) if isinstance(lowercase_ , lowercase_ ) else output_size __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = get_image_size(lowercase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Union[str, Any] = output_size # determine new height and width __SCREAMING_SNAKE_CASE : List[Any] = output_height / input_height __SCREAMING_SNAKE_CASE : int = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width __SCREAMING_SNAKE_CASE : str = scale_width else: # fit height __SCREAMING_SNAKE_CASE : Union[str, Any] = scale_height __SCREAMING_SNAKE_CASE : Optional[Any] = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase_ ) __SCREAMING_SNAKE_CASE : int = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase_ ) return (new_height, new_width) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ['''pixel_values'''] def __init__( self :Optional[Any] , _lowerCamelCase :bool = True , _lowerCamelCase :Dict[str, int] = None , _lowerCamelCase :PILImageResampling = PILImageResampling.BILINEAR , _lowerCamelCase :bool = False , _lowerCamelCase :int = 1 , _lowerCamelCase :bool = True , _lowerCamelCase :Union[int, float] = 1 / 2_5_5 , _lowerCamelCase :bool = True , _lowerCamelCase :Optional[Union[float, List[float]]] = None , _lowerCamelCase :Optional[Union[float, List[float]]] = None , **_lowerCamelCase :List[str] , ): super().__init__(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = size if size is not None else {'''height''': 3_8_4, '''width''': 3_8_4} __SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = do_resize __SCREAMING_SNAKE_CASE : List[Any] = size __SCREAMING_SNAKE_CASE : str = keep_aspect_ratio __SCREAMING_SNAKE_CASE : Optional[int] = ensure_multiple_of __SCREAMING_SNAKE_CASE : int = resample __SCREAMING_SNAKE_CASE : Any = do_rescale __SCREAMING_SNAKE_CASE : int = rescale_factor __SCREAMING_SNAKE_CASE : Optional[int] = do_normalize __SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __SCREAMING_SNAKE_CASE : Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :np.ndarray , _lowerCamelCase :Dict[str, int] , _lowerCamelCase :bool = False , _lowerCamelCase :int = 1 , _lowerCamelCase :PILImageResampling = PILImageResampling.BICUBIC , _lowerCamelCase :Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase :Tuple , ): __SCREAMING_SNAKE_CASE : Optional[Any] = get_size_dict(_lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = get_resize_output_image_size( _lowerCamelCase , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=_lowerCamelCase , multiple=_lowerCamelCase , ) return resize(_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :np.ndarray , _lowerCamelCase :Union[int, float] , _lowerCamelCase :Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase :Tuple , ): return rescale(_lowerCamelCase , scale=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :np.ndarray , _lowerCamelCase :Union[float, List[float]] , _lowerCamelCase :Union[float, List[float]] , _lowerCamelCase :Optional[Union[str, ChannelDimension]] = None , **_lowerCamelCase :Optional[int] , ): return normalize(_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :ImageInput , _lowerCamelCase :bool = None , _lowerCamelCase :int = None , _lowerCamelCase :bool = None , _lowerCamelCase :int = None , _lowerCamelCase :PILImageResampling = None , _lowerCamelCase :bool = None , _lowerCamelCase :float = None , _lowerCamelCase :bool = None , _lowerCamelCase :Optional[Union[float, List[float]]] = None , _lowerCamelCase :Optional[Union[float, List[float]]] = None , _lowerCamelCase :Optional[Union[str, TensorType]] = None , _lowerCamelCase :ChannelDimension = ChannelDimension.FIRST , **_lowerCamelCase :Dict , ): __SCREAMING_SNAKE_CASE : int = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE : int = size if size is not None else self.size __SCREAMING_SNAKE_CASE : Dict = get_size_dict(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio __SCREAMING_SNAKE_CASE : List[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of __SCREAMING_SNAKE_CASE : Optional[Any] = resample if resample is not None else self.resample __SCREAMING_SNAKE_CASE : Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor __SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize __SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else self.image_mean __SCREAMING_SNAKE_CASE : List[Any] = image_std if image_std is not None else self.image_std __SCREAMING_SNAKE_CASE : Dict = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE : Optional[int] = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: __SCREAMING_SNAKE_CASE : Optional[int] = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_rescale: __SCREAMING_SNAKE_CASE : int = [self.rescale(image=_lowerCamelCase , scale=_lowerCamelCase ) for image in images] if do_normalize: __SCREAMING_SNAKE_CASE : str = [self.normalize(image=_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase ) for image in images] __SCREAMING_SNAKE_CASE : int = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] __SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] , _lowerCamelCase :List[Tuple] = None ): __SCREAMING_SNAKE_CASE : int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(_lowerCamelCase ) != len(_lowerCamelCase ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = target_sizes.numpy() __SCREAMING_SNAKE_CASE : Dict = [] for idx in range(len(_lowerCamelCase ) ): __SCREAMING_SNAKE_CASE : int = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Any = logits.argmax(dim=1 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
674
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
1
"""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 _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowerCamelCase = { '''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''' ), }, } _lowerCamelCase = { '''distilbert-base-uncased''': 5_12, '''distilbert-base-uncased-distilled-squad''': 5_12, '''distilbert-base-cased''': 5_12, '''distilbert-base-cased-distilled-squad''': 5_12, '''distilbert-base-german-cased''': 5_12, '''distilbert-base-multilingual-cased''': 5_12, } _lowerCamelCase = { '''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 snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = PRETRAINED_INIT_CONFIGURATION lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] lowerCamelCase__ = DistilBertTokenizer def __init__( self :Optional[int] , _lowerCamelCase :str=None , _lowerCamelCase :Dict=None , _lowerCamelCase :Optional[int]=True , _lowerCamelCase :Optional[Any]="[UNK]" , _lowerCamelCase :Tuple="[SEP]" , _lowerCamelCase :str="[PAD]" , _lowerCamelCase :Union[str, Any]="[CLS]" , _lowerCamelCase :Tuple="[MASK]" , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :List[str]=None , **_lowerCamelCase :Optional[int] , ): super().__init__( _lowerCamelCase , tokenizer_file=_lowerCamelCase , do_lower_case=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , tokenize_chinese_chars=_lowerCamelCase , strip_accents=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : str = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , _lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''' , _lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , _lowerCamelCase ) != tokenize_chinese_chars ): __SCREAMING_SNAKE_CASE : Optional[int] = getattr(_lowerCamelCase , normalizer_state.pop('''type''' ) ) __SCREAMING_SNAKE_CASE : Tuple = do_lower_case __SCREAMING_SNAKE_CASE : List[Any] = strip_accents __SCREAMING_SNAKE_CASE : List[Any] = tokenize_chinese_chars __SCREAMING_SNAKE_CASE : Optional[Any] = normalizer_class(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = do_lower_case def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[Any] , _lowerCamelCase :int=None ): __SCREAMING_SNAKE_CASE : Dict = [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 SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] __SCREAMING_SNAKE_CASE : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): __SCREAMING_SNAKE_CASE : Any = self._tokenizer.model.save(_lowerCamelCase , name=_lowerCamelCase ) return tuple(_lowerCamelCase )
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
1
"""simple docstring""" import math def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = input('''Enter message: ''' ) __SCREAMING_SNAKE_CASE : str = int(input(F'''Enter key [2-{len(lowercase_ ) - 1}]: ''' ) ) __SCREAMING_SNAKE_CASE : Dict = input('''Encryption/Decryption [e/d]: ''' ) if mode.lower().startswith('''e''' ): __SCREAMING_SNAKE_CASE : Tuple = encrypt_message(lowercase_ , lowercase_ ) elif mode.lower().startswith('''d''' ): __SCREAMING_SNAKE_CASE : int = decrypt_message(lowercase_ , lowercase_ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(F'''Output:\n{text + '|'}''' ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = [''''''] * key for col in range(lowercase_ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = col while pointer < len(lowercase_ ): cipher_text[col] += message[pointer] pointer += key return "".join(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = math.ceil(len(lowercase_ ) / key ) __SCREAMING_SNAKE_CASE : Any = key __SCREAMING_SNAKE_CASE : Optional[Any] = (num_cols * num_rows) - len(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = [''''''] * num_cols __SCREAMING_SNAKE_CASE : Optional[int] = 0 __SCREAMING_SNAKE_CASE : Tuple = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): __SCREAMING_SNAKE_CASE : Any = 0 row += 1 return "".join(lowercase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
674
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
1
"""simple docstring""" import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = 0 lowerCamelCase__ = False lowerCamelCase__ = 3.0 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # If no defaults are changed, `to_kwargs` returns an empty dict. self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {'''a''': 2} ) self.assertDictEqual(MockClass(a=2 , b=_lowerCamelCase ).to_kwargs() , {'''a''': 2, '''b''': True} ) self.assertDictEqual(MockClass(a=2 , c=2.2_5 ).to_kwargs() , {'''a''': 2, '''c''': 2.2_5} ) @require_cuda def SCREAMING_SNAKE_CASE_ ( self :Any ): # If no defaults are changed, `to_kwargs` returns an empty dict. __SCREAMING_SNAKE_CASE : str = GradScalerKwargs(init_scale=1_0_2_4 , growth_factor=2 ) AcceleratorState._reset_state() __SCREAMING_SNAKE_CASE : List[Any] = Accelerator(mixed_precision='''fp16''' , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) __SCREAMING_SNAKE_CASE : Union[str, Any] = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 1_0_2_4.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 2_0_0_0 ) self.assertEqual(scaler._enabled , _lowerCamelCase ) @require_multi_gpu def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] execute_subprocess_async(_lowerCamelCase , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = DistributedDataParallelKwargs(bucket_cap_mb=15, find_unused_parameters=True) _lowerCamelCase = Accelerator(kwargs_handlers=[ddp_scaler]) _lowerCamelCase = torch.nn.Linear(1_00, 2_00) _lowerCamelCase = accelerator.prepare(model) # Check the values changed in kwargs _lowerCamelCase = '''''' _lowerCamelCase = model.bucket_bytes_cap // (10_24 * 10_24) if observed_bucket_cap_map != 15: error_msg += f"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += f"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += f"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += f"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += f"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
674
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
1
"""simple docstring""" import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''', } } _lowerCamelCase = { '''albert-base-v1''': 5_12, '''albert-large-v1''': 5_12, '''albert-xlarge-v1''': 5_12, '''albert-xxlarge-v1''': 5_12, '''albert-base-v2''': 5_12, '''albert-large-v2''': 5_12, '''albert-xlarge-v2''': 5_12, '''albert-xxlarge-v2''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self :Tuple , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[Any]=True , _lowerCamelCase :List[str]=True , _lowerCamelCase :List[str]=False , _lowerCamelCase :Tuple="[CLS]" , _lowerCamelCase :Dict="[SEP]" , _lowerCamelCase :Any="<unk>" , _lowerCamelCase :int="[SEP]" , _lowerCamelCase :Optional[Any]="<pad>" , _lowerCamelCase :Optional[Any]="[CLS]" , _lowerCamelCase :str="[MASK]" , _lowerCamelCase :Optional[Dict[str, Any]] = None , **_lowerCamelCase :Dict , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __SCREAMING_SNAKE_CASE : str = ( AddedToken(_lowerCamelCase , lstrip=_lowerCamelCase , rstrip=_lowerCamelCase , normalized=_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else mask_token ) __SCREAMING_SNAKE_CASE : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=_lowerCamelCase , remove_space=_lowerCamelCase , keep_accents=_lowerCamelCase , bos_token=_lowerCamelCase , eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , sep_token=_lowerCamelCase , pad_token=_lowerCamelCase , cls_token=_lowerCamelCase , mask_token=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[Any] = do_lower_case __SCREAMING_SNAKE_CASE : List[Any] = remove_space __SCREAMING_SNAKE_CASE : Optional[Any] = keep_accents __SCREAMING_SNAKE_CASE : Optional[Any] = vocab_file __SCREAMING_SNAKE_CASE : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @property def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return len(self.sp_model ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Any = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[Any] = self.__dict__.copy() __SCREAMING_SNAKE_CASE : Tuple = None return state def __setstate__( self :Optional[int] , _lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : List[str] = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Dict = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Optional[Any] ): if self.remove_space: __SCREAMING_SNAKE_CASE : Any = ''' '''.join(inputs.strip().split() ) else: __SCREAMING_SNAKE_CASE : Any = inputs __SCREAMING_SNAKE_CASE : int = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: __SCREAMING_SNAKE_CASE : Tuple = unicodedata.normalize('''NFKD''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = ''''''.join([c for c in outputs if not unicodedata.combining(_lowerCamelCase )] ) if self.do_lower_case: __SCREAMING_SNAKE_CASE : Optional[Any] = outputs.lower() return outputs def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :str ): __SCREAMING_SNAKE_CASE : Tuple = self.preprocess_text(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [] for piece in pieces: if len(_lowerCamelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): __SCREAMING_SNAKE_CASE : Dict = self.sp_model.EncodeAsPieces(piece[:-1].replace(_lowerCamelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __SCREAMING_SNAKE_CASE : Any = cur_pieces[1:] else: __SCREAMING_SNAKE_CASE : Union[str, Any] = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(_lowerCamelCase ) else: new_pieces.append(_lowerCamelCase ) return new_pieces def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] ): return self.sp_model.PieceToId(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): return self.sp_model.IdToPiece(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[Any] = [] __SCREAMING_SNAKE_CASE : List[str] = '''''' __SCREAMING_SNAKE_CASE : List[str] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : Union[str, Any] = True __SCREAMING_SNAKE_CASE : Union[str, Any] = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] __SCREAMING_SNAKE_CASE : Tuple = [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 SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) if token_ids_a is not None: return [1] + ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] return [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] __SCREAMING_SNAKE_CASE : Tuple = [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 SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[Any] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig _lowerCamelCase = [ '''openmmlab/upernet-convnext-tiny''', # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring _lowerCamelCase = '''UperNetConfig''' class snake_case ( nn.Module ): def __init__( self :Tuple , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :Union[int, Tuple[int, int]] , _lowerCamelCase :Union[int, Tuple[int, int], str] = 0 , _lowerCamelCase :bool = False , _lowerCamelCase :Union[int, Tuple[int, int]] = 1 , ): super().__init__() __SCREAMING_SNAKE_CASE : int = nn.Convad( in_channels=_lowerCamelCase , out_channels=_lowerCamelCase , kernel_size=_lowerCamelCase , padding=_lowerCamelCase , bias=_lowerCamelCase , dilation=_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Optional[Any] = nn.BatchNormad(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = nn.ReLU() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :torch.Tensor ): __SCREAMING_SNAKE_CASE : Optional[int] = self.conv(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.batch_norm(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.activation(_lowerCamelCase ) return output class snake_case ( nn.Module ): def __init__( self :List[str] , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): super().__init__() __SCREAMING_SNAKE_CASE : Optional[Any] = [ nn.AdaptiveAvgPoolad(_lowerCamelCase ), UperNetConvModule(_lowerCamelCase , _lowerCamelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :torch.Tensor ): __SCREAMING_SNAKE_CASE : Optional[Any] = input for layer in self.layers: __SCREAMING_SNAKE_CASE : Any = layer(_lowerCamelCase ) return hidden_state class snake_case ( nn.Module ): def __init__( self :List[Any] , _lowerCamelCase :Tuple[int, ...] , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :bool ): super().__init__() __SCREAMING_SNAKE_CASE : List[str] = pool_scales __SCREAMING_SNAKE_CASE : Any = align_corners __SCREAMING_SNAKE_CASE : Dict = in_channels __SCREAMING_SNAKE_CASE : Optional[Any] = channels __SCREAMING_SNAKE_CASE : List[Any] = [] for i, pool_scale in enumerate(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = UperNetPyramidPoolingBlock(pool_scale=_lowerCamelCase , in_channels=_lowerCamelCase , channels=_lowerCamelCase ) self.blocks.append(_lowerCamelCase ) self.add_module(str(_lowerCamelCase ) , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :torch.Tensor ): __SCREAMING_SNAKE_CASE : List[str] = [] for ppm in self.blocks: __SCREAMING_SNAKE_CASE : Optional[Any] = ppm(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = nn.functional.interpolate( _lowerCamelCase , size=x.size()[2:] , mode='''bilinear''' , align_corners=self.align_corners ) ppm_outs.append(_lowerCamelCase ) return ppm_outs class snake_case ( nn.Module ): def __init__( self :str , _lowerCamelCase :int , _lowerCamelCase :List[Any] ): super().__init__() __SCREAMING_SNAKE_CASE : List[str] = config __SCREAMING_SNAKE_CASE : Union[str, Any] = config.pool_scales # e.g. (1, 2, 3, 6) __SCREAMING_SNAKE_CASE : Optional[int] = in_channels __SCREAMING_SNAKE_CASE : Optional[Any] = config.hidden_size __SCREAMING_SNAKE_CASE : Tuple = False __SCREAMING_SNAKE_CASE : Dict = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module __SCREAMING_SNAKE_CASE : Any = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) __SCREAMING_SNAKE_CASE : Any = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module __SCREAMING_SNAKE_CASE : Tuple = nn.ModuleList() __SCREAMING_SNAKE_CASE : Dict = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer __SCREAMING_SNAKE_CASE : Any = UperNetConvModule(_lowerCamelCase , self.channels , kernel_size=1 ) __SCREAMING_SNAKE_CASE : str = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(_lowerCamelCase ) self.fpn_convs.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): self.apply(self._init_weights ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Union[str, Any] ): if isinstance(_lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :Optional[Any] ): __SCREAMING_SNAKE_CASE : Any = inputs[-1] __SCREAMING_SNAKE_CASE : Tuple = [x] psp_outs.extend(self.psp_modules(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.cat(_lowerCamelCase , dim=1 ) __SCREAMING_SNAKE_CASE : str = self.bottleneck(_lowerCamelCase ) return output def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :torch.Tensor ): # build laterals __SCREAMING_SNAKE_CASE : List[Any] = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(_lowerCamelCase ) ) # build top-down path __SCREAMING_SNAKE_CASE : Any = len(_lowerCamelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __SCREAMING_SNAKE_CASE : Optional[int] = laterals[i - 1].shape[2:] __SCREAMING_SNAKE_CASE : int = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=_lowerCamelCase , mode='''bilinear''' , align_corners=self.align_corners ) # build outputs __SCREAMING_SNAKE_CASE : Union[str, Any] = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __SCREAMING_SNAKE_CASE : Any = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode='''bilinear''' , align_corners=self.align_corners ) __SCREAMING_SNAKE_CASE : int = torch.cat(_lowerCamelCase , dim=1 ) __SCREAMING_SNAKE_CASE : Optional[int] = self.fpn_bottleneck(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = self.classifier(_lowerCamelCase ) return output class snake_case ( nn.Module ): def __init__( self :Any , _lowerCamelCase :Optional[int] , _lowerCamelCase :int = 2 , _lowerCamelCase :int = 3 , _lowerCamelCase :Union[int, Tuple[int, int]] = 1 ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = config __SCREAMING_SNAKE_CASE : str = config.auxiliary_in_channels __SCREAMING_SNAKE_CASE : int = config.auxiliary_channels __SCREAMING_SNAKE_CASE : Optional[Any] = config.auxiliary_num_convs __SCREAMING_SNAKE_CASE : Optional[int] = config.auxiliary_concat_input __SCREAMING_SNAKE_CASE : List[Any] = in_index __SCREAMING_SNAKE_CASE : List[Any] = (kernel_size // 2) * dilation __SCREAMING_SNAKE_CASE : Optional[Any] = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=_lowerCamelCase , padding=_lowerCamelCase , dilation=_lowerCamelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=_lowerCamelCase , padding=_lowerCamelCase , dilation=_lowerCamelCase ) ) if self.num_convs == 0: __SCREAMING_SNAKE_CASE : Any = nn.Identity() else: __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Sequential(*_lowerCamelCase ) if self.concat_input: __SCREAMING_SNAKE_CASE : str = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=_lowerCamelCase , padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE : str = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): self.apply(self._init_weights ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[str] ): if isinstance(_lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :torch.Tensor ): # just take the relevant feature maps __SCREAMING_SNAKE_CASE : Optional[Any] = encoder_hidden_states[self.in_index] __SCREAMING_SNAKE_CASE : Any = self.convs(_lowerCamelCase ) if self.concat_input: __SCREAMING_SNAKE_CASE : Dict = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.classifier(_lowerCamelCase ) return output class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = UperNetConfig lowerCamelCase__ = '''pixel_values''' lowerCamelCase__ = True def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): if isinstance(_lowerCamelCase , _lowerCamelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def SCREAMING_SNAKE_CASE_ ( self :Dict ): self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] , _lowerCamelCase :Optional[Any]=False ): if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE : List[str] = value _lowerCamelCase = R''' Parameters: This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. config ([`UperNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' _lowerCamelCase = R''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( '''UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.''' , __UpperCAmelCase , ) class snake_case ( __UpperCAmelCase ): def __init__( self :str , _lowerCamelCase :Optional[int] ): super().__init__(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) __SCREAMING_SNAKE_CASE : Union[str, Any] = UperNetHead(_lowerCamelCase , in_channels=self.backbone.channels ) __SCREAMING_SNAKE_CASE : Any = UperNetFCNHead(_lowerCamelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('''batch_size, sequence_length''' ) ) @replace_return_docstrings(output_type=_lowerCamelCase , config_class=_CONFIG_FOR_DOC ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :Optional[torch.Tensor] = None , _lowerCamelCase :Optional[bool] = None , _lowerCamelCase :Optional[bool] = None , _lowerCamelCase :Optional[torch.Tensor] = None , _lowerCamelCase :Optional[bool] = None , ): __SCREAMING_SNAKE_CASE : Any = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE : Tuple = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE : Tuple = output_attentions if output_attentions is not None else self.config.output_attentions __SCREAMING_SNAKE_CASE : Tuple = self.backbone.forward_with_filtered_kwargs( _lowerCamelCase , output_hidden_states=_lowerCamelCase , output_attentions=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = outputs.feature_maps __SCREAMING_SNAKE_CASE : List[str] = self.decode_head(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = nn.functional.interpolate(_lowerCamelCase , size=pixel_values.shape[2:] , mode='''bilinear''' , align_corners=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = None if self.auxiliary_head is not None: __SCREAMING_SNAKE_CASE : int = self.auxiliary_head(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = nn.functional.interpolate( _lowerCamelCase , size=pixel_values.shape[2:] , mode='''bilinear''' , align_corners=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = None if labels is not None: if self.config.num_labels == 1: raise ValueError('''The number of labels should be greater than one''' ) else: # compute weighted loss __SCREAMING_SNAKE_CASE : List[Any] = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) __SCREAMING_SNAKE_CASE : List[Any] = loss_fct(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = loss_fct(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: __SCREAMING_SNAKE_CASE : List[Any] = (logits,) + outputs[1:] else: __SCREAMING_SNAKE_CASE : Dict = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=_lowerCamelCase , logits=_lowerCamelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
674
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
1