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 sys import webbrowser import requests from bsa import BeautifulSoup from fake_useragent import UserAgent if __name__ == "__main__": print("Googling.....") __lowerCAmelCase : Optional[int] = """https://www.google.com/search?q=""" + """ """.join(sys.argv[1:]) __lowerCAmelCase : Any = requests.get(url, headers={"UserAgent": UserAgent().random}) # res.raise_for_status() with open("project1a.html", "wb") as out_file: # only for knowing the class for data in res.iter_content(1_00_00): out_file.write(data) __lowerCAmelCase : Optional[Any] = BeautifulSoup(res.text, "html.parser") __lowerCAmelCase : Dict = list(soup.select(".eZt8xd"))[:5] print(len(links)) for link in links: if link.text == "Maps": webbrowser.open(link.get("href")) else: webbrowser.open(F"https://google.com{link.get('href')}")
644
import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class A__ ( A__ ): """simple docstring""" _lowercase = '' _lowercase = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) _lowercase = None # compression type in fsspec. ex: "gzip" _lowercase = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self : List[str] , lowerCamelCase__ : str = "" , lowerCamelCase__ : Optional[str] = None , lowerCamelCase__ : Optional[dict] = None , **lowerCamelCase__ : List[str] ): super().__init__(self , **lowerCamelCase__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode a__ : str = fsspec.open( lowerCamelCase__ , mode="rb" , protocol=lowerCamelCase__ , compression=self.compression , client_kwargs={ "requote_redirect_url": False, # see https://github.com/huggingface/datasets/pull/5459 "trust_env": True, # Enable reading proxy env variables. **(target_options or {}).pop("client_kwargs" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) a__ : Optional[int] = os.path.basename(self.file.path.split("::" )[0] ) a__ : int = ( self.compressed_name[: self.compressed_name.rindex("." )] if "." in self.compressed_name else self.compressed_name ) a__ : List[Any] = None @classmethod def _UpperCamelCase( cls : int , lowerCamelCase__ : int ): # compressed file paths are always relative to the archive root return super()._strip_protocol(lowerCamelCase__ ).lstrip("/" ) def _UpperCamelCase( self : Dict ): if self.dir_cache is None: a__ : Dict = {**self.file.fs.info(self.file.path ), "name": self.uncompressed_name} a__ : int = {f["name"]: f} def _UpperCamelCase( self : Tuple , lowerCamelCase__ : str ): return self.file.open().read() def _UpperCamelCase( self : List[str] , lowerCamelCase__ : str , lowerCamelCase__ : str = "rb" , lowerCamelCase__ : int=None , lowerCamelCase__ : List[str]=True , lowerCamelCase__ : List[str]=None , **lowerCamelCase__ : Optional[Any] , ): a__ : Optional[int] = self._strip_protocol(lowerCamelCase__ ) if mode != "rb": raise ValueError(f'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''' ) return self.file.open() class A__ ( A__ ): """simple docstring""" _lowercase = 'bz2' _lowercase = 'bz2' _lowercase = '.bz2' class A__ ( A__ ): """simple docstring""" _lowercase = 'gzip' _lowercase = 'gzip' _lowercase = '.gz' class A__ ( A__ ): """simple docstring""" _lowercase = 'lz4' _lowercase = 'lz4' _lowercase = '.lz4' class A__ ( A__ ): """simple docstring""" _lowercase = 'xz' _lowercase = 'xz' _lowercase = '.xz' class A__ ( A__ ): """simple docstring""" _lowercase = 'zstd' _lowercase = 'zstd' _lowercase = '.zst' def __init__( self : Optional[int] , lowerCamelCase__ : str , lowerCamelCase__ : str = "rb" , lowerCamelCase__ : Optional[str] = None , lowerCamelCase__ : Optional[dict] = None , lowerCamelCase__ : int = DEFAULT_BLOCK_SIZE , **lowerCamelCase__ : Tuple , ): super().__init__( fo=lowerCamelCase__ , mode=lowerCamelCase__ , target_protocol=lowerCamelCase__ , target_options=lowerCamelCase__ , block_size=lowerCamelCase__ , **lowerCamelCase__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 a__ : Any = self.file.__enter__ class A__ : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase__ : str ): a__ : List[Any] = file_ def __enter__( self : str ): self._file.__enter__() return self def __exit__( self : int , *lowerCamelCase__ : List[str] , **lowerCamelCase__ : int ): self._file.__exit__(*lowerCamelCase__ , **lowerCamelCase__ ) def __iter__( self : List[str] ): return iter(self._file ) def _UpperCamelCase( self : Any ): return next(self._file ) def __getattr__( self : Optional[Any] , lowerCamelCase__ : Tuple ): return getattr(self._file , lowerCamelCase__ ) def fixed_enter(*lowerCamelCase__ : List[str] , **lowerCamelCase__ : str ): return WrappedFile(_enter(*lowerCamelCase__ , **lowerCamelCase__ ) ) a__ : Any = fixed_enter
37
0
"""simple docstring""" import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class _UpperCAmelCase : '''simple docstring''' def __init__( self , A , A=1_3 , A=7 , A=True , A=True , A=False , A=True , A=9_9 , A=6_4 , A=5 , A=4 , A=6_4 , A="gelu" , A=0.1 , A=0.1 , A=5_1_2 , A=1_6 , A=2 , A=0.02 , A=3 , A=4 , A=None , ) -> str: _UpperCAmelCase : Optional[Any] = parent _UpperCAmelCase : List[str] = batch_size _UpperCAmelCase : Tuple = seq_length _UpperCAmelCase : Dict = is_training _UpperCAmelCase : str = use_input_mask _UpperCAmelCase : int = use_token_type_ids _UpperCAmelCase : Any = use_labels _UpperCAmelCase : List[Any] = vocab_size _UpperCAmelCase : Optional[Any] = hidden_size _UpperCAmelCase : int = num_hidden_layers _UpperCAmelCase : Optional[Any] = num_attention_heads _UpperCAmelCase : Union[str, Any] = intermediate_size _UpperCAmelCase : Tuple = hidden_act _UpperCAmelCase : Dict = hidden_dropout_prob _UpperCAmelCase : List[str] = attention_probs_dropout_prob _UpperCAmelCase : Any = max_position_embeddings _UpperCAmelCase : int = type_vocab_size _UpperCAmelCase : List[Any] = type_sequence_label_size _UpperCAmelCase : Tuple = initializer_range _UpperCAmelCase : Any = num_labels _UpperCAmelCase : Optional[int] = num_choices _UpperCAmelCase : Union[str, Any] = scope def __lowerCAmelCase ( self ) -> List[str]: return MPNetConfig.from_pretrained('''microsoft/mpnet-base''' ) def __lowerCAmelCase ( self ) -> Optional[int]: _UpperCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _UpperCAmelCase : Union[str, Any] = None if self.use_input_mask: _UpperCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) _UpperCAmelCase : Optional[Any] = None _UpperCAmelCase : List[Any] = None _UpperCAmelCase : str = None if self.use_labels: _UpperCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _UpperCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) _UpperCAmelCase : Optional[int] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self ) -> Any: return MPNetConfig( 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 , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self , A , A , A , A , A , A ) -> Optional[Any]: _UpperCAmelCase : Union[str, Any] = MPNetModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _UpperCAmelCase : int = model(lowerCamelCase__ , lowerCamelCase__ ) _UpperCAmelCase : str = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCAmelCase ( self , A , A , A , A , A , A ) -> int: _UpperCAmelCase : Union[str, Any] = MPNetForQuestionAnswering(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _UpperCAmelCase : Optional[int] = model( lowerCamelCase__ , attention_mask=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 __lowerCAmelCase ( self , A , A , A , A , A , A ) -> int: _UpperCAmelCase : Union[str, Any] = self.num_labels _UpperCAmelCase : Tuple = MPNetForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _UpperCAmelCase : Tuple = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self , A , A , A , A , A , A ) -> List[str]: _UpperCAmelCase : str = self.num_choices _UpperCAmelCase : List[Any] = MPNetForMultipleChoice(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _UpperCAmelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _UpperCAmelCase : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _UpperCAmelCase : List[Any] = model( lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self , A , A , A , A , A , A ) -> Optional[Any]: _UpperCAmelCase : Any = self.num_labels _UpperCAmelCase : Any = MPNetForTokenClassification(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _UpperCAmelCase : int = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self ) -> List[Any]: _UpperCAmelCase : Any = self.prepare_config_and_inputs() (_UpperCAmelCase) : Optional[Any] = config_and_inputs _UpperCAmelCase : Optional[int] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _UpperCAmelCase ( A__ ,A__ ,unittest.TestCase ): '''simple docstring''' a__ =( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) a__ =( { '''feature-extraction''': MPNetModel, '''fill-mask''': MPNetForMaskedLM, '''question-answering''': MPNetForQuestionAnswering, '''text-classification''': MPNetForSequenceClassification, '''token-classification''': MPNetForTokenClassification, '''zero-shot''': MPNetForSequenceClassification, } if is_torch_available() else {} ) a__ =False a__ =True def __lowerCAmelCase ( self ) -> List[Any]: _UpperCAmelCase : str = MPNetModelTester(self ) _UpperCAmelCase : List[Any] = ConfigTester(self , config_class=lowerCamelCase__ , hidden_size=3_7 ) def __lowerCAmelCase ( self ) -> Optional[Any]: self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Optional[Any]: _UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> Optional[Any]: _UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> Optional[Any]: _UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> str: _UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> Union[str, Any]: _UpperCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*lowerCamelCase__ ) @require_torch class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def __lowerCAmelCase ( self ) -> Optional[int]: _UpperCAmelCase : Dict = MPNetModel.from_pretrained('''microsoft/mpnet-base''' ) _UpperCAmelCase : List[Any] = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) _UpperCAmelCase : List[str] = model(lowerCamelCase__ )[0] _UpperCAmelCase : Any = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape , lowerCamelCase__ ) _UpperCAmelCase : Tuple = torch.tensor( [[[-0.0_550, 0.1_943, -0.0_740], [-0.0_562, 0.2_211, -0.0_579], [-0.0_437, 0.3_337, -0.0_641]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1E-4 ) )
506
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCamelCase_ ( __a , __a , __a ) -> Optional[Any]: a__ : Union[str, Any] = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value") a__ : Union[str, Any] = ( ("layer.", "layer_"), ("word_embeddings.weight", "word_embeddings"), ("position_embeddings.weight", "position_embeddings"), ("token_type_embeddings.weight", "token_type_embeddings"), (".", "/"), ("LayerNorm/weight", "LayerNorm/gamma"), ("LayerNorm/bias", "LayerNorm/beta"), ("weight", "kernel"), ) if not os.path.isdir(__a ): os.makedirs(__a ) a__ : Any = model.state_dict() def to_tf_var_name(__a ): for patt, repl in iter(__a ): a__ : Tuple = name.replace(__a , __a ) return f'''bert/{name}''' def create_tf_var(__a , __a , __a ): a__ : Tuple = tf.dtypes.as_dtype(tensor.dtype ) a__ : Dict = tf.get_variable(dtype=__a , shape=tensor.shape , name=__a , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(__a ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: a__ : int = to_tf_var_name(__a ) a__ : Union[str, Any] = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): a__ : int = torch_tensor.T a__ : Optional[Any] = create_tf_var(tensor=__a , name=__a , session=__a ) tf.keras.backend.set_value(__a , __a ) a__ : int = session.run(__a ) print(f'''Successfully created {tf_name}: {np.allclose(__a , __a )}''' ) a__ : Any = tf.train.Saver(tf.trainable_variables() ) saver.save(__a , os.path.join(__a , model_name.replace("-" , "_" ) + ".ckpt" ) ) def UpperCamelCase_ ( __a=None ) -> int: a__ : Dict = argparse.ArgumentParser() parser.add_argument("--model_name" , type=__a , required=__a , help="model name e.g. bert-base-uncased" ) parser.add_argument( "--cache_dir" , type=__a , default=__a , required=__a , help="Directory containing pytorch model" ) parser.add_argument("--pytorch_model_path" , type=__a , required=__a , help="/path/to/<pytorch-model-name>.bin" ) parser.add_argument("--tf_cache_dir" , type=__a , required=__a , help="Directory in which to save tensorflow model" ) a__ : Optional[Any] = parser.parse_args(__a ) a__ : Tuple = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=__a , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
37
0
'''simple docstring''' import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def _lowercase ( lowerCamelCase__ : Any, lowerCamelCase__ : Optional[Any], lowerCamelCase__ : Union[str, Any] ): # Initialise PyTorch model _a = TaConfig.from_json_file(__a ) print(F'''Building PyTorch model from configuration: {config}''' ) _a = TaForConditionalGeneration(__a ) # Load weights from tf checkpoint load_tf_weights_in_ta(__a, __a, __a ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(__a ) if __name__ == "__main__": __snake_case : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) __snake_case : Tuple = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
131
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class A__ : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase__ : List[str] , lowerCamelCase__ : str=13 , lowerCamelCase__ : Optional[Any]=2 , lowerCamelCase__ : Any=24 , lowerCamelCase__ : Optional[Any]=16 , lowerCamelCase__ : int=True , lowerCamelCase__ : List[str]=True , lowerCamelCase__ : List[Any]=32 , lowerCamelCase__ : List[str]=5 , lowerCamelCase__ : Dict=4 , lowerCamelCase__ : Optional[Any]=37 , lowerCamelCase__ : Any="gelu" , lowerCamelCase__ : Union[str, Any]=0.1 , lowerCamelCase__ : Optional[int]=0.1 , lowerCamelCase__ : str=10 , lowerCamelCase__ : Optional[Any]=0.02 , lowerCamelCase__ : str=None , lowerCamelCase__ : List[str]=2 , lowerCamelCase__ : Optional[Any]=2 , ): a__ : str = parent a__ : Any = batch_size a__ : Dict = patch_size a__ : List[Any] = max_length a__ : str = num_mel_bins a__ : Optional[Any] = is_training a__ : Optional[int] = use_labels a__ : List[Any] = hidden_size a__ : str = num_hidden_layers a__ : Any = num_attention_heads a__ : Union[str, Any] = intermediate_size a__ : List[str] = hidden_act a__ : str = hidden_dropout_prob a__ : Tuple = attention_probs_dropout_prob a__ : List[Any] = type_sequence_label_size a__ : Any = initializer_range a__ : str = scope a__ : List[str] = frequency_stride a__ : Union[str, Any] = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) a__ : List[Any] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 a__ : List[str] = (self.max_length - self.patch_size) // self.time_stride + 1 a__ : Tuple = frequency_out_dimension * time_out_dimension a__ : List[str] = num_patches + 2 def _UpperCamelCase( self : List[str] ): a__ : Any = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) a__ : List[Any] = None if self.use_labels: a__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : List[str] = self.get_config() return config, input_values, labels def _UpperCamelCase( self : Optional[int] ): return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def _UpperCamelCase( self : Union[str, Any] , lowerCamelCase__ : Tuple , lowerCamelCase__ : int , lowerCamelCase__ : Optional[int] ): a__ : List[Any] = ASTModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() a__ : Dict = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase( self : str ): a__ : Dict = self.prepare_config_and_inputs() ( ( a__ ), ( a__ ), ( a__ ), ) : Optional[int] = config_and_inputs a__ : List[Any] = {"input_values": input_values} return config, inputs_dict @require_torch class A__ ( A__ , A__ , unittest.TestCase ): """simple docstring""" _lowercase = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) _lowercase = ( {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel} if is_torch_available() else {} ) _lowercase = False _lowercase = False _lowercase = False _lowercase = False def _UpperCamelCase( self : Union[str, Any] , lowerCamelCase__ : int , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Dict ): if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def _UpperCamelCase( self : str ): a__ : str = ASTModelTester(self ) a__ : Any = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ , hidden_size=37 ) def _UpperCamelCase( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason="AST does not use inputs_embeds" ) def _UpperCamelCase( self : List[str] ): pass def _UpperCamelCase( self : Optional[int] ): a__, a__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Any = model_class(lowerCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) a__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase__ , nn.Linear ) ) def _UpperCamelCase( self : Tuple ): a__, a__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Dict = model_class(lowerCamelCase__ ) a__ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Optional[int] = [*signature.parameters.keys()] a__ : Optional[Any] = ["input_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) def _UpperCamelCase( self : Optional[Any] ): a__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) @slow def _UpperCamelCase( self : int ): for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Union[str, Any] = ASTModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def UpperCamelCase_ ( ) -> Any: a__ : Optional[int] = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" ) a__, a__ : List[str] = torchaudio.load(__a ) return audio, sampling_rate @require_torch @require_torchaudio class A__ ( unittest.TestCase ): """simple docstring""" @cached_property def _UpperCamelCase( self : List[str] ): return ( ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ) if is_torchaudio_available() else None ) @slow def _UpperCamelCase( self : Optional[int] ): a__ : int = self.default_feature_extractor a__ : Optional[Any] = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(lowerCamelCase__ ) a__ : Any = self.default_feature_extractor a__, a__ : Dict = prepare_audio() a__ : str = audio.squeeze().numpy() a__ : Any = feature_extractor(lowerCamelCase__ , sampling_rate=lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): a__ : Any = model(**lowerCamelCase__ ) # verify the logits a__ : Union[str, Any] = torch.Size((1, 527) ) self.assertEqual(outputs.logits.shape , lowerCamelCase__ ) a__ : List[str] = torch.tensor([-0.8760, -7.0042, -8.6602] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase__ , atol=1E-4 ) )
37
0
"""simple docstring""" from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP A = logging.get_logger(__name__) # pylint: disable=invalid-name A = """ Examples: ```py >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline >>> import torch >>> pipe_prior = KandinskyPriorPipeline.from_pretrained(\"kandinsky-community/Kandinsky-2-1-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> negative_image_emb = out.negative_image_embeds >>> pipe = KandinskyPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-1\") >>> pipe.to(\"cuda\") >>> image = pipe( ... prompt, ... image_embeds=image_emb, ... negative_image_embeds=negative_image_emb, ... height=768, ... width=768, ... num_inference_steps=100, ... ).images >>> image[0].save(\"cat.png\") ``` """ def _UpperCamelCase ( UpperCamelCase , UpperCamelCase , UpperCamelCase=8 ) -> List[str]: """simple docstring""" __UpperCAmelCase : List[str] = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 __UpperCAmelCase : Optional[Any] = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class a__ ( A__ ): def __init__( self : Dict , UpperCamelCase_ : MultilingualCLIP , UpperCamelCase_ : XLMRobertaTokenizer , UpperCamelCase_ : UNetaDConditionModel , UpperCamelCase_ : Union[DDIMScheduler, DDPMScheduler] , UpperCamelCase_ : VQModel , ): """simple docstring""" super().__init__() self.register_modules( text_encoder=lowerCamelCase__ , tokenizer=lowerCamelCase__ , unet=lowerCamelCase__ , scheduler=lowerCamelCase__ , movq=lowerCamelCase__ , ) __UpperCAmelCase : int = 2 ** (len(self.movq.config.block_out_channels) - 1) def a_ ( self : Any , UpperCamelCase_ : Tuple , UpperCamelCase_ : Any , UpperCamelCase_ : Tuple , UpperCamelCase_ : int , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Optional[int]): """simple docstring""" if latents is None: __UpperCAmelCase : Tuple = randn_tensor(lowerCamelCase__ , generator=lowerCamelCase__ , device=lowerCamelCase__ , dtype=lowerCamelCase__) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}") __UpperCAmelCase : Optional[Any] = latents.to(lowerCamelCase__) __UpperCAmelCase : Tuple = latents * scheduler.init_noise_sigma return latents def a_ ( self : Union[str, Any] , UpperCamelCase_ : Any , UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[str]=None , ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = len(lowerCamelCase__) if isinstance(lowerCamelCase__ , lowerCamelCase__) else 1 # get prompt text embeddings __UpperCAmelCase : List[Any] = self.tokenizer( lowerCamelCase__ , padding="max_length" , truncation=lowerCamelCase__ , max_length=77 , return_attention_mask=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , return_tensors="pt" , ) __UpperCAmelCase : Tuple = text_inputs.input_ids __UpperCAmelCase : Union[str, Any] = self.tokenizer(lowerCamelCase__ , padding="longest" , return_tensors="pt").input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCamelCase__ , lowerCamelCase__): __UpperCAmelCase : Optional[int] = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]) logger.warning( "The following part of your input was truncated because CLIP can only handle sequences up to" F" {self.tokenizer.model_max_length} tokens: {removed_text}") __UpperCAmelCase : Optional[Any] = text_input_ids.to(lowerCamelCase__) __UpperCAmelCase : List[Any] = text_inputs.attention_mask.to(lowerCamelCase__) __UpperCAmelCase : str = self.text_encoder( input_ids=lowerCamelCase__ , attention_mask=lowerCamelCase__) __UpperCAmelCase : Any = prompt_embeds.repeat_interleave(lowerCamelCase__ , dim=0) __UpperCAmelCase : Optional[Any] = text_encoder_hidden_states.repeat_interleave(lowerCamelCase__ , dim=0) __UpperCAmelCase : Optional[int] = text_mask.repeat_interleave(lowerCamelCase__ , dim=0) if do_classifier_free_guidance: __UpperCAmelCase : List[str] if negative_prompt is None: __UpperCAmelCase : Optional[int] = [""] * batch_size elif type(lowerCamelCase__) is not type(lowerCamelCase__): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(lowerCamelCase__)} !=" F" {type(lowerCamelCase__)}.") elif isinstance(lowerCamelCase__ , lowerCamelCase__): __UpperCAmelCase : Dict = [negative_prompt] elif batch_size != len(lowerCamelCase__): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(lowerCamelCase__)}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`.") else: __UpperCAmelCase : Any = negative_prompt __UpperCAmelCase : Any = self.tokenizer( lowerCamelCase__ , padding="max_length" , max_length=77 , truncation=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ , return_tensors="pt" , ) __UpperCAmelCase : Dict = uncond_input.input_ids.to(lowerCamelCase__) __UpperCAmelCase : Dict = uncond_input.attention_mask.to(lowerCamelCase__) __UpperCAmelCase : Any = self.text_encoder( input_ids=lowerCamelCase__ , attention_mask=lowerCamelCase__) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __UpperCAmelCase : Tuple = negative_prompt_embeds.shape[1] __UpperCAmelCase : List[Any] = negative_prompt_embeds.repeat(1 , lowerCamelCase__) __UpperCAmelCase : Dict = negative_prompt_embeds.view(batch_size * num_images_per_prompt , lowerCamelCase__) __UpperCAmelCase : List[str] = uncond_text_encoder_hidden_states.shape[1] __UpperCAmelCase : Dict = uncond_text_encoder_hidden_states.repeat(1 , lowerCamelCase__ , 1) __UpperCAmelCase : List[str] = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , lowerCamelCase__ , -1) __UpperCAmelCase : List[str] = uncond_text_mask.repeat_interleave(lowerCamelCase__ , dim=0) # done duplicates # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes __UpperCAmelCase : List[str] = torch.cat([negative_prompt_embeds, prompt_embeds]) __UpperCAmelCase : Union[str, Any] = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]) __UpperCAmelCase : str = torch.cat([uncond_text_mask, text_mask]) return prompt_embeds, text_encoder_hidden_states, text_mask def a_ ( self : Tuple , UpperCamelCase_ : List[str]=0): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`") __UpperCAmelCase : str = torch.device(F"cuda:{gpu_id}") __UpperCAmelCase : Dict = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase__ , lowerCamelCase__) def a_ ( self : int , UpperCamelCase_ : str=0): """simple docstring""" if is_accelerate_available() and is_accelerate_version(">=" , "0.17.0.dev0"): from accelerate import cpu_offload_with_hook else: raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.") __UpperCAmelCase : List[str] = torch.device(F"cuda:{gpu_id}") if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=lowerCamelCase__) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) __UpperCAmelCase : Optional[int] = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: __UpperCAmelCase : Optional[Any] = cpu_offload_with_hook(lowerCamelCase__ , lowerCamelCase__ , prev_module_hook=lowerCamelCase__) if self.safety_checker is not None: __UpperCAmelCase : List[Any] = cpu_offload_with_hook(self.safety_checker , lowerCamelCase__ , prev_module_hook=lowerCamelCase__) # We'll offload the last model manually. __UpperCAmelCase : Optional[int] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def a_ ( self : Union[str, Any]): """simple docstring""" if not hasattr(self.unet , "_hf_hook"): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase__ , "_hf_hook") and hasattr(module._hf_hook , "execution_device") and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device) return self.device @torch.no_grad() @replace_example_docstring(lowerCamelCase__) def __call__( self : List[Any] , UpperCamelCase_ : Union[str, List[str]] , UpperCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCamelCase_ : Union[torch.FloatTensor, List[torch.FloatTensor]] , UpperCamelCase_ : Optional[Union[str, List[str]]] = None , UpperCamelCase_ : int = 512 , UpperCamelCase_ : int = 512 , UpperCamelCase_ : int = 100 , UpperCamelCase_ : float = 4.0 , UpperCamelCase_ : int = 1 , UpperCamelCase_ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase_ : Optional[torch.FloatTensor] = None , UpperCamelCase_ : Optional[str] = "pil" , UpperCamelCase_ : bool = True , ): """simple docstring""" if isinstance(lowerCamelCase__ , lowerCamelCase__): __UpperCAmelCase : int = 1 elif isinstance(lowerCamelCase__ , lowerCamelCase__): __UpperCAmelCase : List[str] = len(lowerCamelCase__) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase__)}") __UpperCAmelCase : Dict = self._execution_device __UpperCAmelCase : List[str] = batch_size * num_images_per_prompt __UpperCAmelCase : Tuple = guidance_scale > 1.0 __UpperCAmelCase : Optional[int] = self._encode_prompt( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__) if isinstance(lowerCamelCase__ , lowerCamelCase__): __UpperCAmelCase : List[Any] = torch.cat(lowerCamelCase__ , dim=0) if isinstance(lowerCamelCase__ , lowerCamelCase__): __UpperCAmelCase : int = torch.cat(lowerCamelCase__ , dim=0) if do_classifier_free_guidance: __UpperCAmelCase : Any = image_embeds.repeat_interleave(lowerCamelCase__ , dim=0) __UpperCAmelCase : Any = negative_image_embeds.repeat_interleave(lowerCamelCase__ , dim=0) __UpperCAmelCase : List[str] = torch.cat([negative_image_embeds, image_embeds] , dim=0).to( dtype=prompt_embeds.dtype , device=lowerCamelCase__) self.scheduler.set_timesteps(lowerCamelCase__ , device=lowerCamelCase__) __UpperCAmelCase : Union[str, Any] = self.scheduler.timesteps __UpperCAmelCase : Any = self.unet.config.in_channels __UpperCAmelCase : Optional[int] = get_new_h_w(lowerCamelCase__ , lowerCamelCase__ , self.movq_scale_factor) # create initial latent __UpperCAmelCase : Tuple = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(lowerCamelCase__)): # expand the latents if we are doing classifier free guidance __UpperCAmelCase : Optional[int] = torch.cat([latents] * 2) if do_classifier_free_guidance else latents __UpperCAmelCase : Optional[int] = {"text_embeds": prompt_embeds, "image_embeds": image_embeds} __UpperCAmelCase : Dict = self.unet( sample=lowerCamelCase__ , timestep=lowerCamelCase__ , encoder_hidden_states=lowerCamelCase__ , added_cond_kwargs=lowerCamelCase__ , return_dict=lowerCamelCase__ , )[0] if do_classifier_free_guidance: __UpperCAmelCase : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1) __UpperCAmelCase : Tuple = noise_pred.chunk(2) __UpperCAmelCase : Dict = variance_pred.chunk(2) __UpperCAmelCase : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) __UpperCAmelCase : List[str] = torch.cat([noise_pred, variance_pred_text] , dim=1) if not ( hasattr(self.scheduler.config , "variance_type") and self.scheduler.config.variance_type in ["learned", "learned_range"] ): __UpperCAmelCase : Dict = noise_pred.split(latents.shape[1] , dim=1) # compute the previous noisy sample x_t -> x_t-1 __UpperCAmelCase : Tuple = self.scheduler.step( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , generator=lowerCamelCase__ , ).prev_sample # post-processing __UpperCAmelCase : Any = self.movq.decode(lowerCamelCase__ , force_not_quantize=lowerCamelCase__)["sample"] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}") if output_type in ["np", "pil"]: __UpperCAmelCase : Optional[Any] = image * 0.5 + 0.5 __UpperCAmelCase : List[str] = image.clamp(0 , 1) __UpperCAmelCase : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1).float().numpy() if output_type == "pil": __UpperCAmelCase : Tuple = self.numpy_to_pil(lowerCamelCase__) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase__)
77
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase : Optional[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class A__ ( A__ , unittest.TestCase ): """simple docstring""" _lowercase = XGLMTokenizer _lowercase = XGLMTokenizerFast _lowercase = True _lowercase = True def _UpperCamelCase( self : List[Any] ): super().setUp() # We have a SentencePiece fixture for testing a__ : str = XGLMTokenizer(lowerCamelCase__ , keep_accents=lowerCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _UpperCamelCase( self : List[Any] ): a__ : int = "<pad>" a__ : Union[str, 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 _UpperCamelCase( self : Optional[Any] ): a__ : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(len(lowerCamelCase__ ) , 1_008 ) def _UpperCamelCase( self : Dict ): self.assertEqual(self.get_tokenizer().vocab_size , 1_008 ) def _UpperCamelCase( self : Optional[int] ): a__ : str = XGLMTokenizer(lowerCamelCase__ , keep_accents=lowerCamelCase__ ) a__ : List[str] = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowerCamelCase__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) a__ : 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", "s", "é", ".", ] , ) a__ : List[str] = tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) self.assertListEqual( lowerCamelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) a__ : Dict = 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>", ".", ] , ) @cached_property def _UpperCamelCase( self : Dict ): return XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) def _UpperCamelCase( self : Union[str, Any] ): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCamelCase__ , f.name ) a__ : Any = XGLMTokenizer(f.name , keep_accents=lowerCamelCase__ ) a__ : List[str] = pickle.dumps(lowerCamelCase__ ) pickle.loads(lowerCamelCase__ ) def _UpperCamelCase( self : List[Any] ): if not self.test_rust_tokenizer: return a__ : Any = self.get_tokenizer() a__ : Optional[Any] = self.get_rust_tokenizer() a__ : Tuple = "I was born in 92000, and this is falsé." a__ : List[str] = tokenizer.tokenize(lowerCamelCase__ ) a__ : Union[str, Any] = rust_tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Optional[int] = tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) a__ : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : Tuple = tokenizer.encode(lowerCamelCase__ ) a__ : Optional[Any] = rust_tokenizer.encode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) @slow def _UpperCamelCase( self : List[str] ): a__ : Union[str, Any] = "Hello World!" a__ : List[str] = [2, 31_227, 4_447, 35] self.assertListEqual(lowerCamelCase__ , self.big_tokenizer.encode(lowerCamelCase__ ) ) @slow def _UpperCamelCase( self : Union[str, Any] ): a__ : Optional[int] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth" ) # fmt: off a__ : Union[str, Any] = [2, 1_018, 67, 11, 1_988, 2_617, 5_631, 278, 11, 3_407, 48, 71_630, 28_085, 4, 3_234, 157, 13, 6, 5, 6, 4, 3_526, 768, 15, 659, 57, 298, 3_983, 864, 129, 21, 6, 5, 13_675, 377, 652, 7_580, 10_341, 155, 2_817, 422, 1_666, 7, 1_674, 53, 113, 202_277, 17_892, 33, 60, 87, 4, 3_234, 157, 61, 2_667, 52_376, 19, 88, 23, 735] # fmt: on self.assertListEqual(lowerCamelCase__ , self.big_tokenizer.encode(lowerCamelCase__ ) ) @slow def _UpperCamelCase( self : List[Any] ): # fmt: off a__ : Optional[int] = { "input_ids": [[2, 108_825, 1_163, 15, 88_010, 473, 15_898, 157, 13_672, 1_857, 312, 8, 238_021, 1_163, 53, 13_672, 1_857, 312, 8, 53_283, 182_396, 8, 18_566, 16, 36_733, 4_101, 8, 230, 244_017, 122_553, 7, 15, 132_597, 4, 293, 12_511, 7_610, 4, 3_414, 132_597, 9, 4, 32_361, 362, 4, 734, 28_512, 32_569, 18, 4, 32_361, 26_096, 14_982, 73, 18_715, 21_433, 235_261, 15, 492, 12_427, 16, 53, 18_715, 21_433, 65_454, 15, 23_659, 563, 16, 278, 597, 2_843, 595, 7_931, 182_396, 64_186, 22, 886, 595, 132_981, 53, 25_540, 3_449, 43_982, 39_901, 5_951, 878, 330, 4, 27_694, 80_269, 312, 53, 6_517, 11_780, 611, 20_408, 5], [2, 6, 132_597, 67, 42_897, 33, 592, 8, 163_729, 25_540, 361, 136_997, 109_514, 173_230, 7, 501, 60, 102_913, 196, 5_631, 235, 63_243, 473, 6, 231_757, 74, 5_277, 7_905, 53, 3_095, 37_317, 22, 454, 183_874, 5], [2, 268, 31_298, 46_530, 6, 132_935, 43_831, 7, 597, 32, 24, 3_688, 9_865, 5]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase__ , model_name="facebook/xglm-564M" , padding=lowerCamelCase__ , )
37
0
"""simple docstring""" import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType lowerCamelCase_ = None lowerCamelCase_ = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image lowerCamelCase_ = [ np.dtype("|b1"), np.dtype("|u1"), np.dtype("<u2"), np.dtype(">u2"), np.dtype("<i2"), np.dtype(">i2"), np.dtype("<u4"), np.dtype(">u4"), np.dtype("<i4"), np.dtype(">i4"), np.dtype("<f4"), np.dtype(">f4"), np.dtype("<f8"), np.dtype(">f8"), ] @dataclass class _SCREAMING_SNAKE_CASE: SCREAMING_SNAKE_CASE_ : Optional[int] = True SCREAMING_SNAKE_CASE_ : List[str] = None # Automatically constructed SCREAMING_SNAKE_CASE_ : List[str] = '''PIL.Image.Image''' SCREAMING_SNAKE_CASE_ : Any = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = field(default='''Image''' , init=A__ , repr=A__ ) def __call__( self ) -> int: """simple docstring""" return self.pa_type def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): __SCREAMING_SNAKE_CASE :Union[str, Any] = np.array(lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ): return {"path": value, "bytes": None} elif isinstance(lowerCamelCase__ ,lowerCamelCase__ ): return {"path": None, "bytes": value} elif isinstance(lowerCamelCase__ ,np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(lowerCamelCase__ ) elif isinstance(lowerCamelCase__ ,PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(lowerCamelCase__ ) elif value.get('''path''' ) is not None and os.path.isfile(value['''path'''] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get('''path''' )} elif value.get('''bytes''' ) is not None or value.get('''path''' ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('''bytes''' ), "path": value.get('''path''' )} else: raise ValueError( f'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__=None ) -> List[str]: """simple docstring""" if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Image(decode=True) instead.''' ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support decoding images, please install \'Pillow\'.''' ) if token_per_repo_id is None: __SCREAMING_SNAKE_CASE :List[Any] = {} __SCREAMING_SNAKE_CASE :str = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(f'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) else: if is_local_path(lowerCamelCase__ ): __SCREAMING_SNAKE_CASE :Optional[int] = PIL.Image.open(lowerCamelCase__ ) else: __SCREAMING_SNAKE_CASE :Any = path.split('''::''' )[-1] try: __SCREAMING_SNAKE_CASE :Tuple = string_to_dict(lowerCamelCase__ ,config.HUB_DATASETS_URL )["repo_id"] __SCREAMING_SNAKE_CASE :int = token_per_repo_id.get(lowerCamelCase__ ) except ValueError: __SCREAMING_SNAKE_CASE :List[Any] = None with xopen(lowerCamelCase__ ,'''rb''' ,use_auth_token=lowerCamelCase__ ) as f: __SCREAMING_SNAKE_CASE :Tuple = BytesIO(f.read() ) __SCREAMING_SNAKE_CASE :Tuple = PIL.Image.open(bytes_ ) else: __SCREAMING_SNAKE_CASE :int = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def _UpperCamelCase ( self ) -> Union[str, Any]: """simple docstring""" from .features import Value return ( self if self.decode else { "bytes": Value('''binary''' ), "path": Value('''string''' ), } ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: """simple docstring""" if pa.types.is_string(storage.type ): __SCREAMING_SNAKE_CASE :Dict = pa.array([None] * len(lowerCamelCase__ ) ,type=pa.binary() ) __SCREAMING_SNAKE_CASE :List[str] = pa.StructArray.from_arrays([bytes_array, storage] ,['''bytes''', '''path'''] ,mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): __SCREAMING_SNAKE_CASE :str = pa.array([None] * len(lowerCamelCase__ ) ,type=pa.string() ) __SCREAMING_SNAKE_CASE :Tuple = pa.StructArray.from_arrays([storage, path_array] ,['''bytes''', '''path'''] ,mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('''bytes''' ) >= 0: __SCREAMING_SNAKE_CASE :Any = storage.field('''bytes''' ) else: __SCREAMING_SNAKE_CASE :List[str] = pa.array([None] * len(lowerCamelCase__ ) ,type=pa.binary() ) if storage.type.get_field_index('''path''' ) >= 0: __SCREAMING_SNAKE_CASE :Tuple = storage.field('''path''' ) else: __SCREAMING_SNAKE_CASE :List[Any] = pa.array([None] * len(lowerCamelCase__ ) ,type=pa.string() ) __SCREAMING_SNAKE_CASE :Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] ,['''bytes''', '''path'''] ,mask=storage.is_null() ) elif pa.types.is_list(storage.type ): __SCREAMING_SNAKE_CASE :Tuple = pa.array( [encode_np_array(np.array(lowerCamelCase__ ) )['''bytes'''] if arr is not None else None for arr in storage.to_pylist()] ,type=pa.binary() ,) __SCREAMING_SNAKE_CASE :Tuple = pa.array([None] * len(lowerCamelCase__ ) ,type=pa.string() ) __SCREAMING_SNAKE_CASE :Union[str, Any] = pa.StructArray.from_arrays( [bytes_array, path_array] ,['''bytes''', '''path'''] ,mask=bytes_array.is_null() ) return array_cast(lowerCamelCase__ ,self.pa_type ) def _UpperCamelCase ( self ,SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" @no_op_if_value_is_null def path_to_bytes(SCREAMING_SNAKE_CASE__ ): with xopen(lowerCamelCase__ ,'''rb''' ) as f: __SCREAMING_SNAKE_CASE :int = f.read() return bytes_ __SCREAMING_SNAKE_CASE :int = pa.array( [ (path_to_bytes(x['''path'''] ) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None for x in storage.to_pylist() ] ,type=pa.binary() ,) __SCREAMING_SNAKE_CASE :Union[str, Any] = pa.array( [os.path.basename(lowerCamelCase__ ) if path is not None else None for path in storage.field('''path''' ).to_pylist()] ,type=pa.string() ,) __SCREAMING_SNAKE_CASE :Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] ,['''bytes''', '''path'''] ,mask=bytes_array.is_null() ) return array_cast(lowerCamelCase__ ,self.pa_type ) def __lowerCamelCase ( ) -> List[str]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() __SCREAMING_SNAKE_CASE :Union[str, Any] = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def __lowerCamelCase ( a_ : Dict ) -> bytes: __SCREAMING_SNAKE_CASE :Optional[Any] = BytesIO() if image.format in list_image_compression_formats(): __SCREAMING_SNAKE_CASE :List[Any] = image.format else: __SCREAMING_SNAKE_CASE :Union[str, Any] = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__a , format=__a ) return buffer.getvalue() def __lowerCamelCase ( a_ : Union[str, Any] ) -> dict: if hasattr(__a , '''filename''' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__a )} def __lowerCamelCase ( a_ : Optional[Any] ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) __SCREAMING_SNAKE_CASE :List[Any] = array.dtype __SCREAMING_SNAKE_CASE :Tuple = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER __SCREAMING_SNAKE_CASE :Optional[int] = dtype.kind __SCREAMING_SNAKE_CASE :Any = dtype.itemsize __SCREAMING_SNAKE_CASE :int = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: __SCREAMING_SNAKE_CASE :Optional[Any] = np.dtype('''|u1''' ) if dtype_kind not in ["u", "i"]: raise TypeError( f'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.''' ) if dtype is not dest_dtype: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: __SCREAMING_SNAKE_CASE :Optional[int] = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: __SCREAMING_SNAKE_CASE :Optional[Any] = dtype_byteorder + dtype_kind + str(__a ) __SCREAMING_SNAKE_CASE :int = np.dtype(__a ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'''' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}''' ) __SCREAMING_SNAKE_CASE :Tuple = PIL.Image.fromarray(array.astype(__a ) ) return {"path": None, "bytes": image_to_bytes(__a )} def __lowerCamelCase ( a_ : Tuple ) -> List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('''To support encoding images, please install \'Pillow\'.''' ) if objs: __SCREAMING_SNAKE_CASE :Any = first_non_null_value(__a ) if isinstance(__a , __a ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__a , np.ndarray ): __SCREAMING_SNAKE_CASE :Optional[Any] = no_op_if_value_is_null(__a ) return [obj_to_image_dict_func(__a ) for obj in objs] elif isinstance(__a , PIL.Image.Image ): __SCREAMING_SNAKE_CASE :Optional[int] = no_op_if_value_is_null(__a ) return [obj_to_image_dict_func(__a ) for obj in objs] else: return objs else: return objs
498
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def UpperCamelCase_ ( ) -> int: a__ : int = "https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg" a__ : Optional[Any] = Image.open(requests.get(__a , stream=__a ).raw ).convert("RGB" ) return image def UpperCamelCase_ ( __a ) -> Optional[Any]: a__ : Any = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding") ) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding") ) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight") ) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias") ) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight") ) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias") ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((f'''visual_encoder.blocks.{i}.norm1.weight''', f'''vision_model.encoder.layers.{i}.layer_norm1.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.norm1.bias''', f'''vision_model.encoder.layers.{i}.layer_norm1.bias''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.norm2.weight''', f'''vision_model.encoder.layers.{i}.layer_norm2.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.norm2.bias''', f'''vision_model.encoder.layers.{i}.layer_norm2.bias''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.attn.qkv.weight''', f'''vision_model.encoder.layers.{i}.self_attn.qkv.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.attn.proj.weight''', f'''vision_model.encoder.layers.{i}.self_attn.projection.weight''',) ) rename_keys.append((f'''visual_encoder.blocks.{i}.attn.proj.bias''', f'''vision_model.encoder.layers.{i}.self_attn.projection.bias''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc1.weight''', f'''vision_model.encoder.layers.{i}.mlp.fc1.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc1.bias''', f'''vision_model.encoder.layers.{i}.mlp.fc1.bias''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc2.weight''', f'''vision_model.encoder.layers.{i}.mlp.fc2.weight''') ) rename_keys.append((f'''visual_encoder.blocks.{i}.mlp.fc2.bias''', f'''vision_model.encoder.layers.{i}.mlp.fc2.bias''') ) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.embeddings.layernorm.weight") ) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.embeddings.layernorm.bias") ) # fmt: on return rename_keys def UpperCamelCase_ ( __a , __a , __a ) -> List[str]: a__ : Union[str, Any] = dct.pop(__a ) a__ : List[str] = val def UpperCamelCase_ ( __a , __a ) -> Optional[Any]: for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases a__ : Any = state_dict.pop(f'''visual_encoder.blocks.{i}.attn.q_bias''' ) a__ : Tuple = state_dict.pop(f'''visual_encoder.blocks.{i}.attn.v_bias''' ) # next, set bias in the state dict a__ : str = torch.cat((q_bias, torch.zeros_like(__a , requires_grad=__a ), v_bias) ) a__ : int = qkv_bias def UpperCamelCase_ ( __a ) -> Dict: a__ : Tuple = 364 if "coco" in model_name else 224 a__ : int = InstructBlipVisionConfig(image_size=__a ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: a__ : Tuple = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: a__ : Dict = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1 ).to_dict() elif "vicuna-7b" in model_name: a__ : List[Any] = LlamaConfig.from_pretrained("decapoda-research/llama-7b-hf" , vocab_size=32_001 ).to_dict() elif "vicuna-13b" in model_name: a__ : Optional[int] = LlamaConfig.from_pretrained("decapoda-research/llama-13b-hf" , vocab_size=32_001 ).to_dict() else: raise ValueError("Model name not supported" ) # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 a__ : Optional[Any] = InstructBlipQFormerConfig(vocab_size=30_523 ).to_dict() a__ : Any = InstructBlipConfig(vision_config=__a , text_config=__a , qformer_config=__a ) return config, image_size @torch.no_grad() def UpperCamelCase_ ( __a , __a=None , __a=False ) -> int: a__ : Tuple = AutoTokenizer.from_pretrained("bert-base-uncased" , truncation_side="left" ) qformer_tokenizer.add_special_tokens({"bos_token": "[DEC]"} ) if "t5" in model_name: a__ : List[Any] = TaTokenizerFast.from_pretrained("google/flan-t5-xl" , truncation_side="left" ) elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) a__ : Union[str, Any] = LlamaTokenizerFast.from_pretrained( "huggyllama/llama-7b" , truncation_side="left" , bos_token="</s>" , unk_token="</s>" ) tokenizer.add_special_tokens({"pad_token": "[PAD]"} ) a__, a__ : List[str] = get_blipa_config(__a ) a__ : Any = InstructBlipForConditionalGeneration(__a ).eval() a__ : Dict = { "instructblip-vicuna-7b": ("blip2_vicuna_instruct", "vicuna7b"), "instructblip-vicuna-13b": ("blip2_vicuna_instruct", "vicuna13b"), "instructblip-flan-t5-xl": ("blip2_t5_instruct", "flant5xl"), "instructblip-flan-t5-xxl": ("blip2_t5_instruct", "flant5xxl"), } a__, a__ : Dict = model_name_to_original[model_name] # load original model print("Loading original model..." ) a__ : Optional[Any] = "cuda:1" if torch.cuda.is_available() else "cpu" a__ : List[Any] = "cuda:2" if torch.cuda.is_available() else "cpu" a__, a__, a__ : Tuple = load_model_and_preprocess( name=__a , model_type=__a , is_eval=__a , device=__a ) original_model.eval() print("Done!" ) # update state dict keys a__ : Dict = original_model.state_dict() a__ : Optional[int] = create_rename_keys(__a ) for src, dest in rename_keys: rename_key(__a , __a , __a ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): a__ : Optional[int] = state_dict.pop(__a ) if key.startswith("Qformer.bert" ): a__ : List[Any] = key.replace("Qformer.bert" , "qformer" ) if "attention.self" in key: a__ : Any = key.replace("self" , "attention" ) if "llm_proj" in key: a__ : Dict = key.replace("llm_proj" , "language_projection" ) if "t5_proj" in key: a__ : int = key.replace("t5_proj" , "language_projection" ) if key.startswith("llm_model" ): a__ : List[str] = key.replace("llm_model" , "language_model" ) if key.startswith("t5" ): a__ : str = key.replace("t5" , "language" ) a__ : Dict = val # read in qv biases read_in_q_v_bias(__a , __a ) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(__a , strict=__a ) a__ : Union[str, Any] = load_demo_image() a__ : int = "What is unusual about this image?" # create processor a__ : Any = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=__a , image_std=__a ) a__ : Tuple = InstructBlipProcessor( image_processor=__a , tokenizer=__a , qformer_tokenizer=__a , ) a__ : Tuple = processor(images=__a , text=__a , return_tensors="pt" ).to(__a ) # make sure processor creates exact same pixel values a__ : Optional[int] = vis_processors["eval"](__a ).unsqueeze(0 ).to(__a ) a__ : Optional[Any] = inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device ) , __a ) original_model.to(__a ) hf_model.to(__a ) with torch.no_grad(): if "vicuna" in model_name: a__ : str = original_model({"image": original_pixel_values, "text_input": [prompt]} ).logits a__ : List[str] = hf_model(**__a ).logits else: a__ : List[Any] = original_model( {"image": original_pixel_values, "text_input": [prompt], "text_output": ["\n"]} ).logits a__ : str = tokenizer("\n" , return_tensors="pt" ).input_ids.to(__a ) a__ : Dict = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id , -100 ) a__ : Any = hf_model(**__a , labels=__a ).logits print("First values of original logits:" , original_logits[0, :3, :3] ) print("First values of HF logits:" , logits[0, :3, :3] ) # assert values assert original_logits.shape == logits.shape a__ : Tuple = 1e-4 if "vicuna" in model_name else 1e-5 assert torch.allclose(original_logits.to(logits.device ) , __a , atol=__a ) print("Looks ok!" ) print("Generating with original model..." ) a__ : Tuple = original_model.generate({"image": original_pixel_values, "prompt": prompt} , num_beams=5 ) # important: we need to cast the weights of the HF model to the appropriate type print("Generating with HF model..." ) a__ : int = hf_model.generate( **__a , do_sample=__a , num_beams=5 , max_length=256 , min_length=1 , top_p=0.9 , repetition_penalty=1.5 , length_penalty=1.0 , temperature=1 , ) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? a__ : int = 2 print("Original generation:" , __a ) a__ : str = processor.batch_decode(__a , skip_special_tokens=__a ) a__ : str = [text.strip() for text in output_text] print("HF generation:" , __a ) if pytorch_dump_folder_path is not None: processor.save_pretrained(__a ) hf_model.save_pretrained(__a ) if push_to_hub: processor.push_to_hub(f'''Salesforce/{model_name}''' ) hf_model.push_to_hub(f'''Salesforce/{model_name}''' ) if __name__ == "__main__": UpperCamelCase : Any = argparse.ArgumentParser() UpperCamelCase : Optional[int] = [ """instructblip-vicuna-7b""", """instructblip-vicuna-13b""", """instructblip-flan-t5-xl""", """instructblip-flan-t5-xxl""", ] parser.add_argument( """--model_name""", default="""instructblip-flan-t5-xl""", choices=choices, type=str, help="""Path to hf config.json of model to convert""", ) parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model and processor to the hub after converting""", ) UpperCamelCase : Dict = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
37
0
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, 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 MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class a : """simple docstring""" def __init__( self , snake_case_ , snake_case_=2 , snake_case_=True , snake_case_=False , snake_case_=10 , snake_case_=3 , snake_case_=32 * 8 , snake_case_=32 * 8 , snake_case_=4 , snake_case_=64 , ): '''simple docstring''' __UpperCAmelCase: List[str] = parent __UpperCAmelCase: List[Any] = batch_size __UpperCAmelCase: Any = is_training __UpperCAmelCase: Optional[Any] = use_auxiliary_loss __UpperCAmelCase: Dict = num_queries __UpperCAmelCase: Any = num_channels __UpperCAmelCase: List[Any] = min_size __UpperCAmelCase: Dict = max_size __UpperCAmelCase: Dict = num_labels __UpperCAmelCase: str = hidden_dim __UpperCAmelCase: int = hidden_dim def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: List[Any] = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( lowerCamelCase__ ) __UpperCAmelCase: List[str] = torch.ones([self.batch_size, self.min_size, self.max_size] , device=lowerCamelCase__ ) __UpperCAmelCase: List[str] = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=lowerCamelCase__ ) > 0.5 ).float() __UpperCAmelCase: Optional[int] = (torch.rand((self.batch_size, self.num_labels) , device=lowerCamelCase__ ) > 0.5).long() __UpperCAmelCase: Tuple = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Dict = MaskaFormerConfig( hidden_size=self.hidden_dim , ) __UpperCAmelCase: str = self.num_queries __UpperCAmelCase: Tuple = self.num_labels __UpperCAmelCase: Optional[int] = [1, 1, 1, 1] __UpperCAmelCase: Dict = self.num_channels __UpperCAmelCase: int = 64 __UpperCAmelCase: Optional[Any] = 128 __UpperCAmelCase: Optional[int] = self.hidden_dim __UpperCAmelCase: Dict = self.hidden_dim __UpperCAmelCase: Optional[Any] = self.hidden_dim return config def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Union[str, Any] = self.prepare_config_and_inputs() __UpperCAmelCase: Dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def lowercase_ ( self , snake_case_ , snake_case_ ): '''simple docstring''' __UpperCAmelCase: Any = output.encoder_hidden_states __UpperCAmelCase: Optional[Any] = output.pixel_decoder_hidden_states __UpperCAmelCase: str = 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_layers ) def lowercase_ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_=False ): '''simple docstring''' with torch.no_grad(): __UpperCAmelCase: List[str] = MaskaFormerModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() __UpperCAmelCase: int = model(pixel_values=lowerCamelCase__ , pixel_mask=lowerCamelCase__ ) __UpperCAmelCase: List[str] = model(lowerCamelCase__ , output_hidden_states=lowerCamelCase__ ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # 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 lowercase_ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): '''simple docstring''' __UpperCAmelCase: str = MaskaFormerForUniversalSegmentation(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() def comm_check_on_output(snake_case_ ): # 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(): __UpperCAmelCase: Tuple = model(pixel_values=lowerCamelCase__ , pixel_mask=lowerCamelCase__ ) __UpperCAmelCase: int = model(lowerCamelCase__ ) comm_check_on_output(lowerCamelCase__ ) __UpperCAmelCase: Optional[Any] = 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 a ( A__ , A__ , unittest.TestCase ): """simple docstring""" __lowerCAmelCase = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __lowerCAmelCase = {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {} __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Dict = MaskaFormerModelTester(self ) __UpperCAmelCase: List[str] = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(lowerCamelCase__ , **lowerCamelCase__ , output_hidden_states=lowerCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*lowerCamelCase__ ) @unittest.skip(reason="""Mask2Former does not use inputs_embeds""" ) def lowercase_ ( self ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method""" ) def lowercase_ ( self ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former is not a generative model""" ) def lowercase_ ( self ): '''simple docstring''' pass @unittest.skip(reason="""Mask2Former does not use token embeddings""" ) def lowercase_ ( self ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip( reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`""" ) def lowercase_ ( self ): '''simple docstring''' pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def lowercase_ ( self ): '''simple docstring''' pass def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase: Dict = model_class(lowerCamelCase__ ) __UpperCAmelCase: Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase: List[str] = [*signature.parameters.keys()] __UpperCAmelCase: Optional[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) @slow def lowercase_ ( self ): '''simple docstring''' for model_name in ["facebook/mask2former-swin-small-coco-instance"]: __UpperCAmelCase: Union[str, Any] = MaskaFormerModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: int = (self.model_tester.min_size,) * 2 __UpperCAmelCase: Tuple = { "pixel_values": torch.randn((2, 3, *size) , device=lowerCamelCase__ ), "mask_labels": torch.randn((2, 10, *size) , device=lowerCamelCase__ ), "class_labels": torch.zeros(2 , 10 , device=lowerCamelCase__ ).long(), } __UpperCAmelCase: int = self.model_tester.get_config() __UpperCAmelCase: Any = MaskaFormerForUniversalSegmentation(lowerCamelCase__ ).to(lowerCamelCase__ ) __UpperCAmelCase: Optional[int] = model(**lowerCamelCase__ ) self.assertTrue(outputs.loss is not None ) def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(lowerCamelCase__ , **lowerCamelCase__ , output_hidden_states=lowerCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase: Optional[Any] = model_class(lowerCamelCase__ ).to(lowerCamelCase__ ) __UpperCAmelCase: Any = model(**lowerCamelCase__ , output_attentions=lowerCamelCase__ ) self.assertTrue(outputs.attentions is not None ) def lowercase_ ( self ): '''simple docstring''' if not self.model_tester.is_training: return __UpperCAmelCase: Union[str, Any] = self.all_model_classes[1] __UpperCAmelCase: List[str] = self.model_tester.prepare_config_and_inputs() __UpperCAmelCase: Tuple = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.train() __UpperCAmelCase: int = model(lowerCamelCase__ , mask_labels=lowerCamelCase__ , class_labels=lowerCamelCase__ ).loss loss.backward() def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: str = self.all_model_classes[1] __UpperCAmelCase: int = self.model_tester.prepare_config_and_inputs() __UpperCAmelCase: Optional[Any] = True __UpperCAmelCase: str = True __UpperCAmelCase: Any = model_class(lowerCamelCase__ ).to(lowerCamelCase__ ) model.train() __UpperCAmelCase: Union[str, Any] = model(lowerCamelCase__ , mask_labels=lowerCamelCase__ , class_labels=lowerCamelCase__ ) __UpperCAmelCase: Dict = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __UpperCAmelCase: Optional[Any] = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() __UpperCAmelCase: List[Any] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __UpperCAmelCase: List[str] = 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 ) SCREAMING_SNAKE_CASE_ = 1E-4 def UpperCamelCase__ ( ) -> str: __UpperCAmelCase: str = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_vision @slow class a ( unittest.TestCase ): """simple docstring""" @cached_property def lowercase_ ( self ): '''simple docstring''' return "facebook/mask2former-swin-small-coco-instance" @cached_property def lowercase_ ( self ): '''simple docstring''' return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Dict = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ ) __UpperCAmelCase: List[Any] = self.default_image_processor __UpperCAmelCase: List[Any] = prepare_img() __UpperCAmelCase: Optional[Any] = image_processor(lowerCamelCase__ , return_tensors="""pt""" ).to(lowerCamelCase__ ) __UpperCAmelCase: Dict = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowerCamelCase__ , (1, 3, 384, 384) ) with torch.no_grad(): __UpperCAmelCase: str = model(**lowerCamelCase__ ) __UpperCAmelCase: str = torch.tensor( [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]] ).to(lowerCamelCase__ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) ) __UpperCAmelCase: List[str] = torch.tensor( [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]] ).to(lowerCamelCase__ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) ) __UpperCAmelCase: Tuple = torch.tensor( [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]] ).to(lowerCamelCase__ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) ) def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: str = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ ).eval() __UpperCAmelCase: List[Any] = self.default_image_processor __UpperCAmelCase: str = prepare_img() __UpperCAmelCase: Union[str, Any] = image_processor(lowerCamelCase__ , return_tensors="""pt""" ).to(lowerCamelCase__ ) __UpperCAmelCase: str = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowerCamelCase__ , (1, 3, 384, 384) ) with torch.no_grad(): __UpperCAmelCase: Union[str, Any] = model(**lowerCamelCase__ ) # masks_queries_logits __UpperCAmelCase: Tuple = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) __UpperCAmelCase: Optional[int] = [ [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1], [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1], [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5], ] __UpperCAmelCase: int = torch.tensor(lowerCamelCase__ ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) ) # class_queries_logits __UpperCAmelCase: Any = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) __UpperCAmelCase: List[str] = torch.tensor( [ [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2], [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3], [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5], ] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , lowerCamelCase__ , atol=lowerCamelCase__ ) ) def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Optional[Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowerCamelCase__ ).eval() __UpperCAmelCase: List[Any] = self.default_image_processor __UpperCAmelCase: Union[str, Any] = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="""pt""" , ) __UpperCAmelCase: Any = inputs["pixel_values"].to(lowerCamelCase__ ) __UpperCAmelCase: List[Any] = [el.to(lowerCamelCase__ ) for el in inputs["mask_labels"]] __UpperCAmelCase: List[Any] = [el.to(lowerCamelCase__ ) for el in inputs["class_labels"]] with torch.no_grad(): __UpperCAmelCase: List[Any] = model(**lowerCamelCase__ ) self.assertTrue(outputs.loss is not None )
523
def UpperCamelCase_ ( __a , __a ) -> Tuple: a__ : Optional[int] = [0 for i in range(r + 1 )] # nc0 = 1 a__ : Union[str, Any] = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. a__ : Any = min(__a , __a ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
37
0
'''simple docstring''' __lowerCAmelCase : Optional[int] = """Input must be a string of 8 numbers plus letter""" __lowerCAmelCase : Tuple = """TRWAGMYFPDXBNJZSQVHLCKE""" def lowerCAmelCase ( UpperCamelCase__ : Tuple ): """simple docstring""" if not isinstance(__a , __a ): __UpperCAmelCase = f"""Expected string as input, found {type(__a ).__name__}""" raise TypeError(__a ) __UpperCAmelCase = spanish_id.replace('''-''' , '''''' ).upper() if len(__a ) != 9: raise ValueError(__a ) try: __UpperCAmelCase = int(spanish_id_clean[0:8] ) __UpperCAmelCase = spanish_id_clean[8] except ValueError as ex: raise ValueError(__a ) from ex if letter.isdigit(): raise ValueError(__a ) return letter == LOOKUP_LETTERS[number % 2_3] if __name__ == "__main__": import doctest doctest.testmod()
262
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) UpperCamelCase : Optional[Any] = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCamelCase : Optional[Any] = { """vocab_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""", }, """merges_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""", }, """tokenizer_file""": { """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""", }, } UpperCamelCase : Dict = { """allenai/led-base-16384""": 1_6384, } class A__ ( A__ ): """simple docstring""" _lowercase = VOCAB_FILES_NAMES _lowercase = PRETRAINED_VOCAB_FILES_MAP _lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase = LEDTokenizer _lowercase = ['input_ids', 'attention_mask'] def __init__( self : Tuple , lowerCamelCase__ : Any=None , lowerCamelCase__ : List[str]=None , lowerCamelCase__ : Any=None , lowerCamelCase__ : int="replace" , lowerCamelCase__ : Union[str, Any]="<s>" , lowerCamelCase__ : Union[str, Any]="</s>" , lowerCamelCase__ : Tuple="</s>" , lowerCamelCase__ : Optional[int]="<s>" , lowerCamelCase__ : str="<unk>" , lowerCamelCase__ : Any="<pad>" , lowerCamelCase__ : Any="<mask>" , lowerCamelCase__ : Optional[int]=False , lowerCamelCase__ : int=True , **lowerCamelCase__ : Union[str, Any] , ): super().__init__( lowerCamelCase__ , lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , errors=lowerCamelCase__ , bos_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , unk_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , add_prefix_space=lowerCamelCase__ , trim_offsets=lowerCamelCase__ , **lowerCamelCase__ , ) a__ : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase__ ) != add_prefix_space: a__ : List[str] = getattr(lowerCamelCase__ , pre_tok_state.pop("type" ) ) a__ : Optional[Any] = add_prefix_space a__ : List[str] = pre_tok_class(**lowerCamelCase__ ) a__ : Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` a__ : Any = "post_processor" a__ : str = getattr(self.backend_tokenizer , lowerCamelCase__ , lowerCamelCase__ ) if tokenizer_component_instance: a__ : Any = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a__ : Optional[Any] = tuple(state["sep"] ) if "cls" in state: a__ : Optional[Any] = tuple(state["cls"] ) a__ : Optional[int] = False if state.get("add_prefix_space" , lowerCamelCase__ ) != add_prefix_space: a__ : Dict = add_prefix_space a__ : int = True if state.get("trim_offsets" , lowerCamelCase__ ) != trim_offsets: a__ : List[Any] = trim_offsets a__ : List[str] = True if changes_to_apply: a__ : int = getattr(lowerCamelCase__ , state.pop("type" ) ) a__ : int = component_class(**lowerCamelCase__ ) setattr(self.backend_tokenizer , lowerCamelCase__ , lowerCamelCase__ ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def _UpperCamelCase( self : Union[str, Any] ): if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def _UpperCamelCase( self : Optional[int] , lowerCamelCase__ : Union[str, Any] ): a__ : Any = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else value a__ : Union[str, Any] = value def _UpperCamelCase( self : Any , *lowerCamelCase__ : Optional[int] , **lowerCamelCase__ : Optional[Any] ): a__ : List[str] = kwargs.get("is_split_into_words" , lowerCamelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase__ , **lowerCamelCase__ ) def _UpperCamelCase( self : Any , *lowerCamelCase__ : Dict , **lowerCamelCase__ : Optional[Any] ): a__ : Dict = kwargs.get("is_split_into_words" , lowerCamelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase__ , **lowerCamelCase__ ) def _UpperCamelCase( self : Optional[int] , lowerCamelCase__ : str , lowerCamelCase__ : Optional[str] = None ): a__ : List[str] = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__ ) return tuple(lowerCamelCase__ ) def _UpperCamelCase( self : Dict , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Optional[Any]=None ): a__ : Any = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _UpperCamelCase( self : Tuple , lowerCamelCase__ : List[int] , lowerCamelCase__ : Optional[List[int]] = None ): a__ : List[str] = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _UpperCamelCase( self : Dict , lowerCamelCase__ : Union[Dict[str, EncodedInput], BatchEncoding] , lowerCamelCase__ : Optional[int] = None , lowerCamelCase__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , lowerCamelCase__ : Optional[int] = None , lowerCamelCase__ : Optional[bool] = None , ): a__ : str = super()._pad( encoded_inputs=lowerCamelCase__ , max_length=lowerCamelCase__ , padding_strategy=lowerCamelCase__ , pad_to_multiple_of=lowerCamelCase__ , return_attention_mask=lowerCamelCase__ , ) # Load from model defaults if return_attention_mask is None: a__ : Optional[int] = "attention_mask" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: a__ : Tuple = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. a__ : Dict = len(encoded_inputs["global_attention_mask"] ) != len(lowerCamelCase__ ) if needs_to_be_padded: a__ : Union[str, Any] = len(lowerCamelCase__ ) - len(encoded_inputs["global_attention_mask"] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` a__ : List[Any] = ( encoded_inputs["global_attention_mask"] + [-1] * difference ) elif self.padding_side == "left": a__ : Any = [-1] * difference + encoded_inputs[ "global_attention_mask" ] else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return encoded_inputs
37
0
'''simple docstring''' import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class A ( A__ ): """simple docstring""" __a : Any = (PNDMScheduler,) __a : int = (('''num_inference_steps''', 50),) def _UpperCAmelCase ( self , **__lowerCAmelCase ): UpperCamelCase_ : Optional[int] = { "num_train_timesteps": 10_00, "beta_start": 0.00_01, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**lowerCamelCase__ ) return config def _UpperCAmelCase ( self , __lowerCAmelCase=0 , **__lowerCAmelCase ): UpperCamelCase_ : List[str] = dict(self.forward_default_kwargs ) UpperCamelCase_ : Any = kwargs.pop("""num_inference_steps""" , lowerCamelCase__ ) UpperCamelCase_ : Union[str, Any] = self.dummy_sample UpperCamelCase_ : Optional[int] = 0.1 * sample UpperCamelCase_ : List[Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: UpperCamelCase_ : List[Any] = self.get_scheduler_config(**lowerCamelCase__ ) UpperCamelCase_ : str = scheduler_class(**lowerCamelCase__ ) scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals UpperCamelCase_ : Optional[Any] = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase__ ) UpperCamelCase_ : Tuple = scheduler_class.from_pretrained(lowerCamelCase__ ) new_scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals UpperCamelCase_ : Optional[Any] = dummy_past_residuals[:] UpperCamelCase_ : int = scheduler.step_prk(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample UpperCamelCase_ : Optional[Any] = new_scheduler.step_prk(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" UpperCamelCase_ : Optional[Any] = scheduler.step_plms(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample UpperCamelCase_ : Dict = new_scheduler.step_plms(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _UpperCAmelCase ( self ): pass def _UpperCAmelCase ( self , __lowerCAmelCase=0 , **__lowerCAmelCase ): UpperCamelCase_ : List[Any] = dict(self.forward_default_kwargs ) UpperCamelCase_ : List[Any] = kwargs.pop("""num_inference_steps""" , lowerCamelCase__ ) UpperCamelCase_ : int = self.dummy_sample UpperCamelCase_ : List[str] = 0.1 * sample UpperCamelCase_ : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: UpperCamelCase_ : List[str] = self.get_scheduler_config() UpperCamelCase_ : List[str] = scheduler_class(**lowerCamelCase__ ) scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residuals (must be after setting timesteps) UpperCamelCase_ : Optional[int] = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowerCamelCase__ ) UpperCamelCase_ : Optional[Any] = scheduler_class.from_pretrained(lowerCamelCase__ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowerCamelCase__ ) # copy over dummy past residual (must be after setting timesteps) UpperCamelCase_ : Optional[Any] = dummy_past_residuals[:] UpperCamelCase_ : List[str] = scheduler.step_prk(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample UpperCamelCase_ : List[Any] = new_scheduler.step_prk(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" UpperCamelCase_ : Union[str, Any] = scheduler.step_plms(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample UpperCamelCase_ : str = new_scheduler.step_plms(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def _UpperCAmelCase ( self , **__lowerCAmelCase ): UpperCamelCase_ : Union[str, Any] = self.scheduler_classes[0] UpperCamelCase_ : Dict = self.get_scheduler_config(**lowerCamelCase__ ) UpperCamelCase_ : Optional[Any] = scheduler_class(**lowerCamelCase__ ) UpperCamelCase_ : Any = 10 UpperCamelCase_ : List[str] = self.dummy_model() UpperCamelCase_ : Tuple = self.dummy_sample_deter scheduler.set_timesteps(lowerCamelCase__ ) for i, t in enumerate(scheduler.prk_timesteps ): UpperCamelCase_ : Tuple = model(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase_ : str = scheduler.step_prk(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): UpperCamelCase_ : str = model(lowerCamelCase__ , lowerCamelCase__ ) UpperCamelCase_ : Optional[int] = scheduler.step_plms(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ).prev_sample return sample def _UpperCAmelCase ( self ): UpperCamelCase_ : Optional[Any] = dict(self.forward_default_kwargs ) UpperCamelCase_ : Tuple = kwargs.pop("""num_inference_steps""" , lowerCamelCase__ ) for scheduler_class in self.scheduler_classes: UpperCamelCase_ : int = self.get_scheduler_config() UpperCamelCase_ : List[Any] = scheduler_class(**lowerCamelCase__ ) UpperCamelCase_ : Dict = self.dummy_sample UpperCamelCase_ : Tuple = 0.1 * sample if num_inference_steps is not None and hasattr(lowerCamelCase__ , """set_timesteps""" ): scheduler.set_timesteps(lowerCamelCase__ ) elif num_inference_steps is not None and not hasattr(lowerCamelCase__ , """set_timesteps""" ): UpperCamelCase_ : str = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) UpperCamelCase_ : int = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] UpperCamelCase_ : Dict = dummy_past_residuals[:] UpperCamelCase_ : str = scheduler.step_prk(lowerCamelCase__ , 0 , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample UpperCamelCase_ : Union[str, Any] = scheduler.step_prk(lowerCamelCase__ , 1 , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) UpperCamelCase_ : Dict = scheduler.step_plms(lowerCamelCase__ , 0 , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample UpperCamelCase_ : str = scheduler.step_plms(lowerCamelCase__ , 1 , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _UpperCAmelCase ( self ): for timesteps in [1_00, 10_00]: self.check_over_configs(num_train_timesteps=lowerCamelCase__ ) def _UpperCAmelCase ( self ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowerCamelCase__ ) UpperCamelCase_ : str = self.scheduler_classes[0] UpperCamelCase_ : str = self.get_scheduler_config(steps_offset=1 ) UpperCamelCase_ : Optional[Any] = scheduler_class(**lowerCamelCase__ ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [9_01, 8_51, 8_51, 8_01, 8_01, 7_51, 7_51, 7_01, 7_01, 6_51, 6_51, 6_01, 6_01, 5_01, 4_01, 3_01, 2_01, 1_01, 1] ) , ) def _UpperCAmelCase ( self ): for beta_start, beta_end in zip([0.00_01, 0.0_01] , [0.0_02, 0.02] ): self.check_over_configs(beta_start=lowerCamelCase__ , beta_end=lowerCamelCase__ ) def _UpperCAmelCase ( self ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowerCamelCase__ ) def _UpperCAmelCase ( self ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCamelCase__ ) def _UpperCAmelCase ( self ): for t in [1, 5, 10]: self.check_over_forward(time_step=lowerCamelCase__ ) def _UpperCAmelCase ( self ): for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 1_00] ): self.check_over_forward(num_inference_steps=lowerCamelCase__ ) def _UpperCAmelCase ( self ): # earlier version of set_timesteps() caused an error indexing alpha's with inference steps as power of 3 UpperCamelCase_ : Optional[int] = 27 for scheduler_class in self.scheduler_classes: UpperCamelCase_ : int = self.dummy_sample UpperCamelCase_ : Optional[int] = 0.1 * sample UpperCamelCase_ : str = self.get_scheduler_config() UpperCamelCase_ : List[str] = scheduler_class(**lowerCamelCase__ ) scheduler.set_timesteps(lowerCamelCase__ ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): UpperCamelCase_ : Dict = scheduler.step_prk(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ).prev_sample def _UpperCAmelCase ( self ): with self.assertRaises(lowerCamelCase__ ): UpperCamelCase_ : Union[str, Any] = self.scheduler_classes[0] UpperCamelCase_ : Optional[Any] = self.get_scheduler_config() UpperCamelCase_ : Union[str, Any] = scheduler_class(**lowerCamelCase__ ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def _UpperCAmelCase ( self ): UpperCamelCase_ : Union[str, Any] = self.full_loop() UpperCamelCase_ : str = torch.sum(torch.abs(lowerCamelCase__ ) ) UpperCamelCase_ : Dict = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_sum.item() - 1_98.13_18 ) < 1E-2 assert abs(result_mean.item() - 0.25_80 ) < 1E-3 def _UpperCAmelCase ( self ): UpperCamelCase_ : Dict = self.full_loop(prediction_type="""v_prediction""" ) UpperCamelCase_ : Optional[int] = torch.sum(torch.abs(lowerCamelCase__ ) ) UpperCamelCase_ : int = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_sum.item() - 67.39_86 ) < 1E-2 assert abs(result_mean.item() - 0.08_78 ) < 1E-3 def _UpperCAmelCase ( self ): # We specify different beta, so that the first alpha is 0.99 UpperCamelCase_ : Tuple = self.full_loop(set_alpha_to_one=lowerCamelCase__ , beta_start=0.01 ) UpperCamelCase_ : Tuple = torch.sum(torch.abs(lowerCamelCase__ ) ) UpperCamelCase_ : Tuple = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_sum.item() - 2_30.03_99 ) < 1E-2 assert abs(result_mean.item() - 0.29_95 ) < 1E-3 def _UpperCAmelCase ( self ): # We specify different beta, so that the first alpha is 0.99 UpperCamelCase_ : List[str] = self.full_loop(set_alpha_to_one=lowerCamelCase__ , beta_start=0.01 ) UpperCamelCase_ : Optional[int] = torch.sum(torch.abs(lowerCamelCase__ ) ) UpperCamelCase_ : Union[str, Any] = torch.mean(torch.abs(lowerCamelCase__ ) ) assert abs(result_sum.item() - 1_86.94_82 ) < 1E-2 assert abs(result_mean.item() - 0.24_34 ) < 1E-3
208
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer UpperCamelCase : Any = logging.get_logger(__name__) UpperCamelCase : Any = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} UpperCamelCase : Union[str, Any] = { """vocab_file""": { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/vocab.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/vocab.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/vocab.json""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json""", """roberta-large-openai-detector""": ( """https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json""" ), }, """merges_file""": { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/merges.txt""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/merges.txt""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/merges.txt""", """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt""", """roberta-large-openai-detector""": ( """https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt""" ), }, """tokenizer_file""": { """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/tokenizer.json""", """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/tokenizer.json""", """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json""", """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json""", """roberta-base-openai-detector""": ( """https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json""" ), """roberta-large-openai-detector""": ( """https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json""" ), }, } UpperCamelCase : List[str] = { """roberta-base""": 512, """roberta-large""": 512, """roberta-large-mnli""": 512, """distilroberta-base""": 512, """roberta-base-openai-detector""": 512, """roberta-large-openai-detector""": 512, } class A__ ( A__ ): """simple docstring""" _lowercase = VOCAB_FILES_NAMES _lowercase = PRETRAINED_VOCAB_FILES_MAP _lowercase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase = ['input_ids', 'attention_mask'] _lowercase = RobertaTokenizer def __init__( self : List[str] , lowerCamelCase__ : Any=None , lowerCamelCase__ : List[Any]=None , lowerCamelCase__ : Dict=None , lowerCamelCase__ : List[str]="replace" , lowerCamelCase__ : List[str]="<s>" , lowerCamelCase__ : Union[str, Any]="</s>" , lowerCamelCase__ : Any="</s>" , lowerCamelCase__ : Any="<s>" , lowerCamelCase__ : int="<unk>" , lowerCamelCase__ : Any="<pad>" , lowerCamelCase__ : Tuple="<mask>" , lowerCamelCase__ : Any=False , lowerCamelCase__ : Dict=True , **lowerCamelCase__ : Optional[Any] , ): super().__init__( lowerCamelCase__ , lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , errors=lowerCamelCase__ , bos_token=lowerCamelCase__ , eos_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , unk_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , add_prefix_space=lowerCamelCase__ , trim_offsets=lowerCamelCase__ , **lowerCamelCase__ , ) a__ : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase__ ) != add_prefix_space: a__ : Any = getattr(lowerCamelCase__ , pre_tok_state.pop("type" ) ) a__ : int = add_prefix_space a__ : Tuple = pre_tok_class(**lowerCamelCase__ ) a__ : str = add_prefix_space a__ : Tuple = "post_processor" a__ : Dict = getattr(self.backend_tokenizer , lowerCamelCase__ , lowerCamelCase__ ) if tokenizer_component_instance: a__ : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a__ : Tuple = tuple(state["sep"] ) if "cls" in state: a__ : str = tuple(state["cls"] ) a__ : str = False if state.get("add_prefix_space" , lowerCamelCase__ ) != add_prefix_space: a__ : str = add_prefix_space a__ : Any = True if state.get("trim_offsets" , lowerCamelCase__ ) != trim_offsets: a__ : int = trim_offsets a__ : Dict = True if changes_to_apply: a__ : Union[str, Any] = getattr(lowerCamelCase__ , state.pop("type" ) ) a__ : str = component_class(**lowerCamelCase__ ) setattr(self.backend_tokenizer , lowerCamelCase__ , lowerCamelCase__ ) @property def _UpperCamelCase( self : Union[str, Any] ): if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def _UpperCamelCase( self : List[Any] , lowerCamelCase__ : Tuple ): a__ : List[Any] = AddedToken(lowerCamelCase__ , lstrip=lowerCamelCase__ , rstrip=lowerCamelCase__ ) if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else value a__ : List[str] = value def _UpperCamelCase( self : Union[str, Any] , *lowerCamelCase__ : int , **lowerCamelCase__ : int ): a__ : Optional[int] = kwargs.get("is_split_into_words" , lowerCamelCase__ ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase__ , **lowerCamelCase__ ) def _UpperCamelCase( self : Tuple , *lowerCamelCase__ : Dict , **lowerCamelCase__ : List[str] ): a__ : Dict = kwargs.get("is_split_into_words" , lowerCamelCase__ ) assert self.add_prefix_space or not is_split_into_words, ( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase__ , **lowerCamelCase__ ) def _UpperCamelCase( self : str , lowerCamelCase__ : str , lowerCamelCase__ : Optional[str] = None ): a__ : int = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__ ) return tuple(lowerCamelCase__ ) def _UpperCamelCase( self : Optional[int] , lowerCamelCase__ : Dict , lowerCamelCase__ : Optional[int]=None ): a__ : Union[str, Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _UpperCamelCase( self : Dict , lowerCamelCase__ : List[int] , lowerCamelCase__ : Optional[List[int]] = None ): a__ : Tuple = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
37
0
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, 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(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class a__ ( unittest.TestCase ): def __init__( self : Tuple , A_ : Union[str, Any] , A_ : Union[str, Any]=13 , A_ : str=7 , A_ : List[str]=True , A_ : Optional[int]=True , A_ : Union[str, Any]=True , A_ : List[Any]=True , A_ : Tuple=99 , A_ : int=32 , A_ : List[Any]=5 , A_ : str=4 , A_ : str=37 , A_ : Dict="gelu" , A_ : Tuple=0.1 , A_ : Tuple=0.1 , A_ : Tuple=5_12 , A_ : Optional[int]=16 , A_ : List[str]=2 , A_ : Union[str, Any]=0.02 , A_ : List[Any]=4 , ) -> List[str]: """simple docstring""" lowerCamelCase_: Optional[Any] = parent lowerCamelCase_: List[str] = batch_size lowerCamelCase_: str = seq_length lowerCamelCase_: Optional[int] = is_training lowerCamelCase_: Optional[Any] = use_attention_mask lowerCamelCase_: str = use_token_type_ids lowerCamelCase_: Optional[Any] = use_labels lowerCamelCase_: str = vocab_size lowerCamelCase_: Optional[Any] = hidden_size lowerCamelCase_: str = num_hidden_layers lowerCamelCase_: int = num_attention_heads lowerCamelCase_: Tuple = intermediate_size lowerCamelCase_: List[Any] = hidden_act lowerCamelCase_: Optional[int] = hidden_dropout_prob lowerCamelCase_: Any = attention_probs_dropout_prob lowerCamelCase_: str = max_position_embeddings lowerCamelCase_: Optional[int] = type_vocab_size lowerCamelCase_: Tuple = type_sequence_label_size lowerCamelCase_: Optional[int] = initializer_range lowerCamelCase_: List[Any] = num_choices def lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" lowerCamelCase_: Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase_: int = None if self.use_attention_mask: lowerCamelCase_: str = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase_: Dict = None if self.use_token_type_ids: lowerCamelCase_: Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase_: int = RobertaPreLayerNormConfig( 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 lowerCAmelCase ( self : Tuple ) -> Optional[int]: """simple docstring""" lowerCamelCase_: str = self.prepare_config_and_inputs() lowerCamelCase_: Optional[Any] = config_and_inputs lowerCamelCase_: Optional[int] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def lowerCAmelCase ( self : str ) -> Tuple: """simple docstring""" lowerCamelCase_: Optional[Any] = self.prepare_config_and_inputs() lowerCamelCase_: Union[str, Any] = config_and_inputs lowerCamelCase_: Optional[int] = True lowerCamelCase_: Dict = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCamelCase_: Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class a__ ( A__ , unittest.TestCase ): _A = True _A = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def lowerCAmelCase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_: Dict = FlaxRobertaPreLayerNormModelTester(self ) @slow def lowerCAmelCase ( self : Dict ) -> Dict: """simple docstring""" for model_class_name in self.all_model_classes: lowerCamelCase_: List[str] = model_class_name.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=lowerCamelCase__ ) lowerCamelCase_: Optional[int] = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase__ ) @require_flax class a__ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : Dict ) -> List[Any]: """simple docstring""" lowerCamelCase_: Any = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=lowerCamelCase__ ) lowerCamelCase_: str = np.array([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] , dtype=jnp.intaa ) lowerCamelCase_: int = model(lowerCamelCase__ )[0] lowerCamelCase_: int = [1, 11, 5_02_65] self.assertEqual(list(output.shape ) , lowerCamelCase__ ) # compare the actual values for a slice. lowerCamelCase_: str = np.array( [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1e-4 ) ) @slow def lowerCAmelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" lowerCamelCase_: int = FlaxRobertaPreLayerNormModel.from_pretrained("""andreasmadsen/efficient_mlm_m0.40""" , from_pt=lowerCamelCase__ ) lowerCamelCase_: Any = np.array([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] , dtype=jnp.intaa ) lowerCamelCase_: str = model(lowerCamelCase__ )[0] # compare the actual values for a slice. lowerCamelCase_: Optional[Any] = np.array( [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , lowerCamelCase__ , atol=1e-4 ) )
423
from statistics import mean, stdev def UpperCamelCase_ ( __a , __a = 3 ) -> list: a__ : List[str] = min(__a ) a__ : str = max(__a ) # normalize data return [round((x - x_min) / (x_max - x_min) , __a ) for x in data] def UpperCamelCase_ ( __a , __a = 3 ) -> list: a__ : str = mean(__a ) a__ : List[str] = stdev(__a ) # standardize data return [round((x - mu) / (sigma) , __a ) for x in data]
37
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _snake_case : List[str] = { """configuration_bridgetower""": [ """BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BridgeTowerConfig""", """BridgeTowerTextConfig""", """BridgeTowerVisionConfig""", ], """processing_bridgetower""": ["""BridgeTowerProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = ["""BridgeTowerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : str = [ """BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST""", """BridgeTowerForContrastiveLearning""", """BridgeTowerForImageAndTextRetrieval""", """BridgeTowerForMaskedLM""", """BridgeTowerModel""", """BridgeTowerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys _snake_case : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
53
def UpperCamelCase_ ( __a = 50 ) -> int: a__ : Tuple = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f"""{solution() = }""")
37
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __A : Optional[Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class A_ (A__ , unittest.TestCase ): UpperCAmelCase__ = XGLMTokenizer UpperCAmelCase__ = XGLMTokenizerFast UpperCAmelCase__ = True UpperCAmelCase__ = True def _lowercase ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XGLMTokenizer(lowerCamelCase__ , keep_accents=lowerCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = "<pad>" UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase__ ) , lowerCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase__ ) , lowerCamelCase__ ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(len(lowerCamelCase__ ) , 1_0_0_8 ) def _lowercase ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_8 ) def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = XGLMTokenizer(lowerCamelCase__ , keep_accents=lowerCamelCase__ ) UpperCAmelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCamelCase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) UpperCAmelCase = 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''', '''é''', '''.''', ] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) self.assertListEqual( lowerCamelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) UpperCAmelCase = 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>''', '''.''', ] , ) @cached_property def _lowercase ( self ): '''simple docstring''' return XGLMTokenizer.from_pretrained('''facebook/xglm-564M''' ) def _lowercase ( self ): '''simple docstring''' with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCamelCase__ , f.name ) UpperCAmelCase = XGLMTokenizer(f.name , keep_accents=lowerCamelCase__ ) UpperCAmelCase = pickle.dumps(lowerCamelCase__ ) pickle.loads(lowerCamelCase__ ) def _lowercase ( self ): '''simple docstring''' if not self.test_rust_tokenizer: return UpperCAmelCase = self.get_tokenizer() UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = "I was born in 92000, and this is falsé." UpperCAmelCase = tokenizer.tokenize(lowerCamelCase__ ) UpperCAmelCase = rust_tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) UpperCAmelCase = tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) UpperCAmelCase = rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) UpperCAmelCase = self.get_rust_tokenizer() UpperCAmelCase = tokenizer.encode(lowerCamelCase__ ) UpperCAmelCase = rust_tokenizer.encode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) @slow def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = "Hello World!" UpperCAmelCase = [2, 3_1_2_2_7, 4_4_4_7, 3_5] self.assertListEqual(lowerCamelCase__ , self.big_tokenizer.encode(lowerCamelCase__ ) ) @slow def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth" ) # fmt: off UpperCAmelCase = [2, 1_0_1_8, 6_7, 1_1, 1_9_8_8, 2_6_1_7, 5_6_3_1, 2_7_8, 1_1, 3_4_0_7, 4_8, 7_1_6_3_0, 2_8_0_8_5, 4, 3_2_3_4, 1_5_7, 1_3, 6, 5, 6, 4, 3_5_2_6, 7_6_8, 1_5, 6_5_9, 5_7, 2_9_8, 3_9_8_3, 8_6_4, 1_2_9, 2_1, 6, 5, 1_3_6_7_5, 3_7_7, 6_5_2, 7_5_8_0, 1_0_3_4_1, 1_5_5, 2_8_1_7, 4_2_2, 1_6_6_6, 7, 1_6_7_4, 5_3, 1_1_3, 2_0_2_2_7_7, 1_7_8_9_2, 3_3, 6_0, 8_7, 4, 3_2_3_4, 1_5_7, 6_1, 2_6_6_7, 5_2_3_7_6, 1_9, 8_8, 2_3, 7_3_5] # fmt: on self.assertListEqual(lowerCamelCase__ , self.big_tokenizer.encode(lowerCamelCase__ ) ) @slow def _lowercase ( self ): '''simple docstring''' UpperCAmelCase = { "input_ids": [[2, 1_0_8_8_2_5, 1_1_6_3, 1_5, 8_8_0_1_0, 4_7_3, 1_5_8_9_8, 1_5_7, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 2_3_8_0_2_1, 1_1_6_3, 5_3, 1_3_6_7_2, 1_8_5_7, 3_1_2, 8, 5_3_2_8_3, 1_8_2_3_9_6, 8, 1_8_5_6_6, 1_6, 3_6_7_3_3, 4_1_0_1, 8, 2_3_0, 2_4_4_0_1_7, 1_2_2_5_5_3, 7, 1_5, 1_3_2_5_9_7, 4, 2_9_3, 1_2_5_1_1, 7_6_1_0, 4, 3_4_1_4, 1_3_2_5_9_7, 9, 4, 3_2_3_6_1, 3_6_2, 4, 7_3_4, 2_8_5_1_2, 3_2_5_6_9, 1_8, 4, 3_2_3_6_1, 2_6_0_9_6, 1_4_9_8_2, 7_3, 1_8_7_1_5, 2_1_4_3_3, 2_3_5_2_6_1, 1_5, 4_9_2, 1_2_4_2_7, 1_6, 5_3, 1_8_7_1_5, 2_1_4_3_3, 6_5_4_5_4, 1_5, 2_3_6_5_9, 5_6_3, 1_6, 2_7_8, 5_9_7, 2_8_4_3, 5_9_5, 7_9_3_1, 1_8_2_3_9_6, 6_4_1_8_6, 2_2, 8_8_6, 5_9_5, 1_3_2_9_8_1, 5_3, 2_5_5_4_0, 3_4_4_9, 4_3_9_8_2, 3_9_9_0_1, 5_9_5_1, 8_7_8, 3_3_0, 4, 2_7_6_9_4, 8_0_2_6_9, 3_1_2, 5_3, 6_5_1_7, 1_1_7_8_0, 6_1_1, 2_0_4_0_8, 5], [2, 6, 1_3_2_5_9_7, 6_7, 4_2_8_9_7, 3_3, 5_9_2, 8, 1_6_3_7_2_9, 2_5_5_4_0, 3_6_1, 1_3_6_9_9_7, 1_0_9_5_1_4, 1_7_3_2_3_0, 7, 5_0_1, 6_0, 1_0_2_9_1_3, 1_9_6, 5_6_3_1, 2_3_5, 6_3_2_4_3, 4_7_3, 6, 2_3_1_7_5_7, 7_4, 5_2_7_7, 7_9_0_5, 5_3, 3_0_9_5, 3_7_3_1_7, 2_2, 4_5_4, 1_8_3_8_7_4, 5], [2, 2_6_8, 3_1_2_9_8, 4_6_5_3_0, 6, 1_3_2_9_3_5, 4_3_8_3_1, 7, 5_9_7, 3_2, 2_4, 3_6_8_8, 9_8_6_5, 5]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase__ , model_name='''facebook/xglm-564M''' , padding=lowerCamelCase__ , )
130
class A__ : """simple docstring""" def __init__( self : List[Any] , lowerCamelCase__ : str , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str] ): a__ : str = name a__ : Optional[int] = value a__ : Dict = weight def __repr__( self : Union[str, Any] ): return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})''' def _UpperCamelCase( self : Dict ): return self.value def _UpperCamelCase( self : Optional[Any] ): return self.name def _UpperCamelCase( self : Optional[Any] ): return self.weight def _UpperCamelCase( self : Optional[int] ): return self.value / self.weight def UpperCamelCase_ ( __a , __a , __a ) -> Optional[Any]: a__ : Optional[Any] = [] for i in range(len(__a ) ): menu.append(Things(name[i] , value[i] , weight[i] ) ) return menu def UpperCamelCase_ ( __a , __a , __a ) -> Union[str, Any]: a__ : List[str] = sorted(__a , key=__a , reverse=__a ) a__ : List[Any] = [] a__, a__ : Union[str, Any] = 0.0, 0.0 for i in range(len(__a ) ): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i] ) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def UpperCamelCase_ ( ) -> Union[str, Any]: pass if __name__ == "__main__": import doctest doctest.testmod()
37
0
"""simple docstring""" def _UpperCAmelCase ( lowerCamelCase__ = 100_0000 ): """simple docstring""" lowerCAmelCase__ = limit + 1 lowerCAmelCase__ = [0] * limit for first_term in range(1 , __a ): for n in range(__a , __a , __a ): lowerCAmelCase__ = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a lowerCAmelCase__ = sum(1 for x in frequency[1:limit] if x == 10 ) return count if __name__ == "__main__": print(F"{solution() = }")
644
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class A__ ( A__ ): """simple docstring""" def __init__( self : Dict , lowerCamelCase__ : Union[str, "sqlalchemy.sql.Selectable"] , lowerCamelCase__ : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , lowerCamelCase__ : Optional[Features] = None , lowerCamelCase__ : str = None , lowerCamelCase__ : bool = False , **lowerCamelCase__ : Optional[int] , ): super().__init__(features=lowerCamelCase__ , cache_dir=lowerCamelCase__ , keep_in_memory=lowerCamelCase__ , **lowerCamelCase__ ) a__ : str = Sql( cache_dir=lowerCamelCase__ , features=lowerCamelCase__ , sql=lowerCamelCase__ , con=lowerCamelCase__ , **lowerCamelCase__ , ) def _UpperCamelCase( self : Tuple ): a__ : Optional[Any] = None a__ : Dict = None a__ : Union[str, Any] = None a__ : Union[str, Any] = None self.builder.download_and_prepare( download_config=lowerCamelCase__ , download_mode=lowerCamelCase__ , verification_mode=lowerCamelCase__ , base_path=lowerCamelCase__ , ) # Build dataset for splits a__ : List[str] = self.builder.as_dataset( split="train" , verification_mode=lowerCamelCase__ , in_memory=self.keep_in_memory ) return dataset class A__ : """simple docstring""" def __init__( self : List[Any] , lowerCamelCase__ : Dataset , lowerCamelCase__ : str , lowerCamelCase__ : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , lowerCamelCase__ : Optional[int] = None , lowerCamelCase__ : Optional[int] = None , **lowerCamelCase__ : Optional[Any] , ): if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) a__ : Any = dataset a__ : str = name a__ : Tuple = con a__ : List[Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE a__ : Any = num_proc a__ : Tuple = to_sql_kwargs def _UpperCamelCase( self : List[Any] ): a__ : Any = self.to_sql_kwargs.pop("sql" , lowerCamelCase__ ) a__ : int = self.to_sql_kwargs.pop("con" , lowerCamelCase__ ) a__ : int = self.to_sql_kwargs.pop("index" , lowerCamelCase__ ) a__ : int = self._write(index=lowerCamelCase__ , **self.to_sql_kwargs ) return written def _UpperCamelCase( self : Any , lowerCamelCase__ : List[str] ): a__, a__, a__ : Union[str, Any] = args a__ : Any = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs a__ : Tuple = query_table( table=self.dataset.data , key=slice(lowerCamelCase__ , offset + self.batch_size ) , indices=self.dataset._indices , ) a__ : str = batch.to_pandas() a__ : List[Any] = df.to_sql(self.name , self.con , index=lowerCamelCase__ , **lowerCamelCase__ ) return num_rows or len(lowerCamelCase__ ) def _UpperCamelCase( self : Optional[Any] , lowerCamelCase__ : Optional[int] , **lowerCamelCase__ : Optional[Any] ): a__ : str = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: a__, a__ : List[str] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , lowerCamelCase__ , lowerCamelCase__ )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating SQL from Arrow format" , ): written += num_rows return written
37
0
"""simple docstring""" import math import qiskit def lowerCamelCase_ (UpperCamelCase__ : Optional[int] = 1 , UpperCamelCase__ : int = 1 , UpperCamelCase__ : Optional[int] = 1 ): if ( isinstance(__a , __a ) or isinstance(__a , __a ) or isinstance(__a , __a ) ): raise TypeError('''inputs must be integers.''' ) if (input_a < 0) or (input_a < 0) or (carry_in < 0): raise ValueError('''inputs must be positive.''' ) if ( (math.floor(__a ) != input_a) or (math.floor(__a ) != input_a) or (math.floor(__a ) != carry_in) ): raise ValueError('''inputs must be exact integers.''' ) if (input_a > 2) or (input_a > 2) or (carry_in > 2): raise ValueError('''inputs must be less or equal to 2.''' ) # build registers _UpperCAmelCase : Union[str, Any] = qiskit.QuantumRegister(4 , '''qr''' ) _UpperCAmelCase : Optional[Any] = qiskit.ClassicalRegister(2 , '''cr''' ) # list the entries _UpperCAmelCase : int = [input_a, input_a, carry_in] _UpperCAmelCase : str = qiskit.QuantumCircuit(__a , __a ) for i in range(0 , 3 ): if entry[i] == 2: quantum_circuit.h(__a ) # for hadamard entries elif entry[i] == 1: quantum_circuit.x(__a ) # for 1 entries elif entry[i] == 0: quantum_circuit.i(__a ) # for 0 entries # build the circuit quantum_circuit.ccx(0 , 1 , 3 ) # ccx = toffoli gate quantum_circuit.cx(0 , 1 ) quantum_circuit.ccx(1 , 2 , 3 ) quantum_circuit.cx(1 , 2 ) quantum_circuit.cx(0 , 1 ) quantum_circuit.measure([2, 3] , __a ) # measure the last two qbits _UpperCAmelCase : Any = qiskit.Aer.get_backend('''aer_simulator''' ) _UpperCAmelCase : List[Any] = qiskit.execute(__a , __a , shots=1000 ) return job.result().get_counts(__a ) if __name__ == "__main__": print(f"Total sum count for state is: {quantum_full_adder(1, 1, 1)}")
506
import math from datetime import datetime, timedelta def UpperCamelCase_ ( __a ) -> datetime: a__ : Union[str, Any] = year % 19 a__ : List[str] = year % 4 a__ : str = year % 7 a__ : Any = math.floor(year / 100 ) a__ : List[str] = math.floor((13 + 8 * leap_day_inhibits) / 25 ) a__ : Optional[int] = leap_day_inhibits / 4 a__ : Union[str, Any] = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 a__ : Dict = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 a__ : Any = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon a__ : List[Any] = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(__a , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(__a , 4 , 18 ) else: return datetime(__a , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1994, 2000, 2010, 2021, 2023): UpperCamelCase : Tuple = """will be""" if year > datetime.now().year else """was""" print(f"""Easter in {year} {tense} {gauss_easter(year)}""")
37
0
'''simple docstring''' import unittest from transformers import SqueezeBertConfig, 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, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class A ( A__ ): def __init__( self , snake_case_ , snake_case_=1_3 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=False , snake_case_=True , snake_case_=9_9 , snake_case_=3_2 , snake_case_=5 , snake_case_=4 , snake_case_=6_4 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=5_1_2 , snake_case_=1_6 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , snake_case_=2 , snake_case_=2 , snake_case_=2 , snake_case_=2 , snake_case_=4 , snake_case_=1 , ) -> Optional[int]: _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_input_mask _a = use_token_type_ids _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = num_labels _a = num_choices _a = scope _a = q_groups _a = k_groups _a = v_groups _a = post_attention_groups _a = intermediate_groups _a = output_groups def __lowerCAmelCase ( self ) -> Optional[Any]: _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = None if self.use_input_mask: _a = random_attention_mask([self.batch_size, self.seq_length] ) _a = None _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = ids_tensor([self.batch_size] , self.num_choices ) _a = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self ) -> Any: return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> List[Any]: _a = SqueezeBertModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _a = model(lowerCamelCase__ , lowerCamelCase__ ) _a = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: _a = SqueezeBertForMaskedLM(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _a = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Any: _a = SqueezeBertForQuestionAnswering(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _a = model( lowerCamelCase__ , attention_mask=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 __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> str: _a = self.num_labels _a = SqueezeBertForSequenceClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _a = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Dict: _a = self.num_labels _a = SqueezeBertForTokenClassification(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _a = model(lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: _a = self.num_choices _a = SqueezeBertForMultipleChoice(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() _a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = model( lowerCamelCase__ , attention_mask=lowerCamelCase__ , labels=lowerCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self ) -> int: _a = self.prepare_config_and_inputs() (_a) = config_and_inputs _a = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A ( A__ , A__ , unittest.TestCase ): __UpperCAmelCase : Optional[int] = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase : Optional[Any] = ( { """feature-extraction""": SqueezeBertModel, """fill-mask""": SqueezeBertForMaskedLM, """question-answering""": SqueezeBertForQuestionAnswering, """text-classification""": SqueezeBertForSequenceClassification, """token-classification""": SqueezeBertForTokenClassification, """zero-shot""": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Optional[Any] = True __UpperCAmelCase : Tuple = False def __lowerCAmelCase ( self ) -> Optional[Any]: _a = SqueezeBertModelTester(self ) _a = ConfigTester(self , config_class=lowerCamelCase__ , dim=3_7 ) def __lowerCAmelCase ( self ) -> Any: self.config_tester.run_common_tests() def __lowerCAmelCase ( self ) -> Tuple: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> str: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> Any: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> str: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> Any: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*lowerCamelCase__ ) def __lowerCAmelCase ( self ) -> Optional[int]: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*lowerCamelCase__ ) @slow def __lowerCAmelCase ( self ) -> List[str]: for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a = SqueezeBertModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @require_sentencepiece @require_tokenizers @require_torch class A ( unittest.TestCase ): @slow def __lowerCAmelCase ( self ) -> int: _a = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli" ) _a = torch.tensor([[1, 2_9_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 1_3, 1_5_8_8, 2]] ) _a = model(lowerCamelCase__ )[0] _a = torch.Size((1, 3) ) self.assertEqual(output.shape , lowerCamelCase__ ) _a = torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(lowerCamelCase__ , lowerCamelCase__ , atol=1E-4 ) )
131
import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def UpperCamelCase_ ( __a ) -> Union[str, Any]: if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class A__ ( nn.Module ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase__ : nn.Module , lowerCamelCase__ : int ): super().__init__() a__ : int = module a__ : Any = nn.Sequential( nn.Linear(module.in_features , lowerCamelCase__ , bias=lowerCamelCase__ ) , nn.Linear(lowerCamelCase__ , module.out_features , bias=lowerCamelCase__ ) , ) a__ : Tuple = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=lowerCamelCase__ ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def _UpperCamelCase( self : Union[str, Any] , lowerCamelCase__ : Optional[int] , *lowerCamelCase__ : int , **lowerCamelCase__ : Dict ): return self.module(lowerCamelCase__ , *lowerCamelCase__ , **lowerCamelCase__ ) + self.adapter(lowerCamelCase__ ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class A__ ( unittest.TestCase ): """simple docstring""" _lowercase = 'bigscience/bloom-1b7' # Constant values _lowercase = 2.1_09_65_95_52_69_25_74 _lowercase = 'Hello my name is' _lowercase = set() EXPECTED_OUTPUTS.add('Hello my name is John and I am a professional photographer. I' ) EXPECTED_OUTPUTS.add('Hello my name is John.\nI am a friend of your father.\n' ) EXPECTED_OUTPUTS.add('Hello my name is John Doe, I am a student at the University' ) _lowercase = 1_0 def _UpperCamelCase( self : Dict ): # Models and tokenizer a__ : List[str] = AutoTokenizer.from_pretrained(self.model_name ) class A__ ( A__ ): """simple docstring""" def _UpperCamelCase( self : Union[str, Any] ): super().setUp() # Models and tokenizer a__ : List[Any] = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map="auto" ) a__ : Union[str, Any] = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) def _UpperCamelCase( self : List[Any] ): del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def _UpperCamelCase( self : List[Any] ): a__ : str = self.model_abit.config self.assertTrue(hasattr(lowerCamelCase__ , "quantization_config" ) ) a__ : Optional[Any] = config.to_dict() a__ : int = config.to_diff_dict() a__ : List[str] = config.to_json_string() def _UpperCamelCase( self : int ): from bitsandbytes.nn import Paramsabit a__ : List[Any] = self.model_fpaa.get_memory_footprint() a__ : str = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) a__ : Optional[Any] = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def _UpperCamelCase( self : Tuple ): from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(lowerCamelCase__ , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def _UpperCamelCase( self : str ): a__ : Dict = self.tokenizer(self.input_text , return_tensors="pt" ) a__ : Tuple = self.model_abit.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=lowerCamelCase__ ) , self.EXPECTED_OUTPUTS ) def _UpperCamelCase( self : List[Any] ): a__ : Optional[Any] = BitsAndBytesConfig() a__ : Optional[int] = True a__ : int = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=lowerCamelCase__ , device_map="auto" ) a__ : str = self.tokenizer(self.input_text , return_tensors="pt" ) a__ : int = model_abit_from_config.generate( input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=lowerCamelCase__ ) , self.EXPECTED_OUTPUTS ) def _UpperCamelCase( self : Dict ): with self.assertRaises(lowerCamelCase__ ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(lowerCamelCase__ ) def _UpperCamelCase( self : Union[str, Any] ): a__ : int = BitsAndBytesConfig() with self.assertRaises(lowerCamelCase__ ): a__ : Dict = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=lowerCamelCase__ , load_in_abit=lowerCamelCase__ , device_map="auto" , bnb_abit_quant_type="nf4" , ) def _UpperCamelCase( self : int ): with self.assertRaises(lowerCamelCase__ ): # Tries with `str` self.model_abit.to("cpu" ) with self.assertRaises(lowerCamelCase__ ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(lowerCamelCase__ ): # Tries with a `device` self.model_abit.to(torch.device("cuda:0" ) ) with self.assertRaises(lowerCamelCase__ ): # Tries with a `device` self.model_abit.float() with self.assertRaises(lowerCamelCase__ ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything a__ : int = self.tokenizer(self.input_text , return_tensors="pt" ) a__ : Any = self.model_fpaa.to(torch.floataa ) a__ : List[Any] = self.model_fpaa.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error a__ : Tuple = self.model_fpaa.to("cpu" ) # Check this does not throw an error a__ : Tuple = self.model_fpaa.half() # Check this does not throw an error a__ : Dict = self.model_fpaa.float() def _UpperCamelCase( self : Dict ): a__ : List[str] = AutoModelForSeqaSeqLM.from_pretrained("t5-small" , load_in_abit=lowerCamelCase__ , device_map="auto" ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class A__ ( unittest.TestCase ): """simple docstring""" @classmethod def _UpperCamelCase( cls : str ): a__ : Dict = "t5-small" a__ : List[Any] = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense a__ : int = AutoTokenizer.from_pretrained(cls.model_name ) a__ : str = "Translate in German: Hello, my dog is cute" def _UpperCamelCase( self : Optional[int] ): gc.collect() torch.cuda.empty_cache() def _UpperCamelCase( self : Optional[int] ): from transformers import TaForConditionalGeneration a__ : List[Any] = TaForConditionalGeneration._keep_in_fpaa_modules a__ : Optional[Any] = None # test with `t5-small` a__ : Any = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) a__ : Dict = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) a__ : int = model.generate(**lowerCamelCase__ ) # test with `flan-t5-small` a__ : Dict = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) a__ : Dict = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) a__ : Any = model.generate(**lowerCamelCase__ ) a__ : Union[str, Any] = modules def _UpperCamelCase( self : List[Any] ): import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` a__ : List[str] = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) a__ : Union[str, Any] = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) a__ : int = model.generate(**lowerCamelCase__ ) # test with `flan-t5-small` a__ : int = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) a__ : Any = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) a__ : Optional[int] = model.generate(**lowerCamelCase__ ) class A__ ( A__ ): """simple docstring""" def _UpperCamelCase( self : List[str] ): super().setUp() # model_name a__ : Union[str, Any] = "bigscience/bloom-560m" a__ : Union[str, Any] = "t5-small" # Different types of model a__ : int = AutoModel.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) # Sequence classification model a__ : Dict = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) # CausalLM model a__ : str = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) # Seq2seq model a__ : Dict = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=lowerCamelCase__ , device_map="auto" ) def _UpperCamelCase( self : List[Any] ): del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def _UpperCamelCase( self : Union[str, Any] ): from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class A__ ( A__ ): """simple docstring""" def _UpperCamelCase( self : Dict ): super().setUp() def _UpperCamelCase( self : int ): del self.pipe gc.collect() torch.cuda.empty_cache() def _UpperCamelCase( self : Tuple ): a__ : int = pipeline( "text-generation" , model=self.model_name , model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass a__ : Tuple = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]["generated_text"] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class A__ ( A__ ): """simple docstring""" def _UpperCamelCase( self : Tuple ): super().setUp() def _UpperCamelCase( self : List[Any] ): a__ : str = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=lowerCamelCase__ , device_map="balanced" ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model a__ : List[Any] = self.tokenizer(self.input_text , return_tensors="pt" ) # Second real batch a__ : List[Any] = model_parallel.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=lowerCamelCase__ ) , self.EXPECTED_OUTPUTS ) class A__ ( A__ ): """simple docstring""" def _UpperCamelCase( self : Dict ): a__ : Any = "facebook/opt-350m" super().setUp() def _UpperCamelCase( self : int ): if version.parse(importlib.metadata.version("bitsandbytes" ) ) < version.parse("0.37.0" ): return # Step 1: freeze all parameters a__ : Tuple = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=lowerCamelCase__ ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): a__ : Any = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability a__ : Tuple = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(lowerCamelCase__ ) ): a__ : Dict = LoRALayer(module.q_proj , rank=16 ) a__ : List[Any] = LoRALayer(module.k_proj , rank=16 ) a__ : List[Any] = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch a__ : Dict = self.tokenizer("Test batch " , return_tensors="pt" ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): a__ : Optional[Any] = model.forward(**lowerCamelCase__ ) out.logits.norm().backward() for module in model.modules(): if isinstance(lowerCamelCase__ , lowerCamelCase__ ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(lowerCamelCase__ , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class A__ ( A__ ): """simple docstring""" _lowercase = 'gpt2-xl' _lowercase = 3.31_91_85_48_54_15_21_87
37
0
"""simple docstring""" import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import ops from transformers import GradientAccumulator, create_optimizer @require_tf class a__ ( unittest.TestCase ): def a_ ( self : Optional[Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any]): """simple docstring""" self.assertEqual(len(lowerCamelCase__) , len(lowerCamelCase__)) for a, b in zip(lowerCamelCase__ , lowerCamelCase__): self.assertAlmostEqual(lowerCamelCase__ , lowerCamelCase__ , delta=lowerCamelCase__) def a_ ( self : Union[str, Any]): """simple docstring""" __UpperCAmelCase : List[str] = GradientAccumulator() accumulator([tf.constant([1.0, 2.0])]) accumulator([tf.constant([-2.0, 1.0])]) accumulator([tf.constant([-1.0, 2.0])]) with self.assertRaises(lowerCamelCase__): accumulator([tf.constant([1.0, 1.0]), tf.constant([2.0, 2.0])]) self.assertEqual(accumulator.step , 3) self.assertEqual(len(accumulator.gradients) , 1) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [-2.0, 5.0] , tol=1e-2) accumulator.reset() self.assertEqual(accumulator.step , 0) self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() , [0.0, 0.0] , tol=1e-2) def a_ ( self : List[Any]): """simple docstring""" __UpperCAmelCase : Tuple = None ops.enable_eager_execution_internal() __UpperCAmelCase : Dict = tf.config.list_physical_devices("CPU") if len(lowerCamelCase__) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()]) __UpperCAmelCase : Optional[int] = tf.config.list_logical_devices(device_type="CPU") __UpperCAmelCase : Tuple = tf.distribute.MirroredStrategy(devices=devices[:2]) with strategy.scope(): __UpperCAmelCase : List[Any] = GradientAccumulator() __UpperCAmelCase : str = tf.Variable([4.0, 3.0]) __UpperCAmelCase : Union[str, Any] = create_optimizer(5e-5 , 10 , 5) __UpperCAmelCase : Optional[int] = tf.Variable([0.0, 0.0] , trainable=lowerCamelCase__) def accumulate_on_replica(UpperCamelCase_ : Any): accumulator([gradient]) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable]))) @tf.function def accumulate(UpperCamelCase_ : Any , UpperCamelCase_ : Optional[Any]): with strategy.scope(): __UpperCAmelCase : Tuple = strategy.experimental_local_results(lowerCamelCase__) local_variables[0].assign(lowerCamelCase__) local_variables[1].assign(lowerCamelCase__) strategy.run(lowerCamelCase__ , args=(gradient_placeholder,)) @tf.function def apply_grad(): with strategy.scope(): strategy.run(lowerCamelCase__) def _check_local_values(UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[int]): __UpperCAmelCase : Optional[int] = strategy.experimental_local_results(accumulator._gradients[0]) self.assertListAlmostEqual(values[0].value() , lowerCamelCase__ , tol=1e-2) self.assertListAlmostEqual(values[1].value() , lowerCamelCase__ , tol=1e-2) accumulate([1.0, 2.0] , [-1.0, 1.0]) accumulate([3.0, -1.0] , [-1.0, -1.0]) accumulate([-2.0, 2.0] , [3.0, -2.0]) self.assertEqual(accumulator.step , 3) _check_local_values([2.0, 3.0] , [1.0, -2.0]) apply_grad() self.assertListAlmostEqual(variable.value() , [4.0, 3.0] , tol=1e-2) accumulator.reset() self.assertEqual(accumulator.step , 0) _check_local_values([0.0, 0.0] , [0.0, 0.0])
77
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class A__ : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Optional[int]=100 , lowerCamelCase__ : str=13 , lowerCamelCase__ : Optional[int]=30 , lowerCamelCase__ : Union[str, Any]=2 , lowerCamelCase__ : Tuple=3 , lowerCamelCase__ : List[Any]=True , lowerCamelCase__ : Tuple=True , lowerCamelCase__ : int=32 , lowerCamelCase__ : Union[str, Any]=4 , lowerCamelCase__ : Dict=4 , lowerCamelCase__ : Union[str, Any]=37 , lowerCamelCase__ : List[Any]="gelu" , lowerCamelCase__ : List[Any]=0.1 , lowerCamelCase__ : int=0.1 , lowerCamelCase__ : Union[str, Any]=10 , lowerCamelCase__ : str=0.02 , lowerCamelCase__ : Tuple=3 , lowerCamelCase__ : Dict=None , lowerCamelCase__ : List[str]=[0, 1, 2, 3] , ): a__ : Dict = parent a__ : Dict = 100 a__ : Optional[int] = batch_size a__ : Union[str, Any] = image_size a__ : Any = patch_size a__ : Optional[Any] = num_channels a__ : int = is_training a__ : List[str] = use_labels a__ : Optional[Any] = hidden_size a__ : List[Any] = num_hidden_layers a__ : str = num_attention_heads a__ : str = intermediate_size a__ : int = hidden_act a__ : List[Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = type_sequence_label_size a__ : Optional[Any] = initializer_range a__ : List[str] = scope a__ : int = out_indices a__ : List[str] = num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) a__ : Optional[int] = (image_size // patch_size) ** 2 a__ : Union[str, Any] = num_patches + 1 def _UpperCamelCase( self : int ): a__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a__ : Optional[Any] = None a__ : Tuple = None if self.use_labels: a__ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) a__ : Optional[int] = self.get_config() return config, pixel_values, labels, pixel_labels def _UpperCamelCase( self : Tuple ): return BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase__ , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def _UpperCamelCase( self : Dict , lowerCamelCase__ : int , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : int , lowerCamelCase__ : Any ): a__ : str = BeitModel(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() a__ : List[str] = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCamelCase( self : Tuple , lowerCamelCase__ : List[str] , lowerCamelCase__ : Any , lowerCamelCase__ : List[str] , lowerCamelCase__ : Tuple ): a__ : int = BeitForMaskedImageModeling(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() a__ : List[Any] = model(lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def _UpperCamelCase( self : str , lowerCamelCase__ : Any , lowerCamelCase__ : str , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Any ): a__ : List[str] = self.type_sequence_label_size a__ : Optional[Any] = BeitForImageClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() a__ : str = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images a__ : Optional[Any] = 1 a__ : List[str] = BeitForImageClassification(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() a__ : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) a__ : Union[str, Any] = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _UpperCamelCase( self : Any , lowerCamelCase__ : str , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Any , lowerCamelCase__ : Dict ): a__ : int = self.num_labels a__ : List[str] = BeitForSemanticSegmentation(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() a__ : Tuple = model(lowerCamelCase__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) a__ : str = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _UpperCamelCase( self : Optional[int] ): a__ : Any = self.prepare_config_and_inputs() a__, a__, a__, a__ : Union[str, Any] = config_and_inputs a__ : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class A__ ( A__ , A__ , unittest.TestCase ): """simple docstring""" _lowercase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) _lowercase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) _lowercase = False _lowercase = False _lowercase = False def _UpperCamelCase( self : Any ): a__ : int = BeitModelTester(self ) a__ : Optional[Any] = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ , hidden_size=37 ) def _UpperCamelCase( self : List[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="BEiT does not use inputs_embeds" ) def _UpperCamelCase( self : str ): pass @require_torch_multi_gpu @unittest.skip(reason="BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def _UpperCamelCase( self : Dict ): pass def _UpperCamelCase( self : Optional[Any] ): a__, a__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : List[str] = model_class(lowerCamelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) a__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase__ , nn.Linear ) ) def _UpperCamelCase( self : str ): a__, a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : int = model_class(lowerCamelCase__ ) a__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Optional[int] = [*signature.parameters.keys()] a__ : Any = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase__ ) def _UpperCamelCase( self : List[Any] ): a__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def _UpperCamelCase( self : int ): a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase__ ) def _UpperCamelCase( self : List[Any] ): a__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ ) def _UpperCamelCase( self : Optional[int] ): a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__ ) def _UpperCamelCase( self : Optional[Any] ): if not self.model_tester.is_training: return a__, a__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() a__ : str = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(lowerCamelCase__ ), BeitForMaskedImageModeling]: continue a__ : List[str] = model_class(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.train() a__ : Any = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) a__ : Tuple = model(**lowerCamelCase__ ).loss loss.backward() def _UpperCamelCase( self : Tuple ): a__, a__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return a__ : List[Any] = False a__ : List[str] = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(lowerCamelCase__ ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue a__ : Optional[Any] = model_class(lowerCamelCase__ ) model.gradient_checkpointing_enable() model.to(lowerCamelCase__ ) model.train() a__ : Union[str, Any] = self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ , return_labels=lowerCamelCase__ ) a__ : int = model(**lowerCamelCase__ ).loss loss.backward() def _UpperCamelCase( self : List[str] ): a__, a__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() a__ : Dict = _config_zero_init(lowerCamelCase__ ) for model_class in self.all_model_classes: a__ : str = model_class(config=lowerCamelCase__ ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @slow def _UpperCamelCase( self : Optional[int] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Tuple = BeitModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def UpperCamelCase_ ( ) -> Any: a__ : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class A__ ( unittest.TestCase ): """simple docstring""" @cached_property def _UpperCamelCase( self : Optional[int] ): return BeitImageProcessor.from_pretrained("microsoft/beit-base-patch16-224" ) if is_vision_available() else None @slow def _UpperCamelCase( self : str ): a__ : int = BeitForMaskedImageModeling.from_pretrained("microsoft/beit-base-patch16-224-pt22k" ).to(lowerCamelCase__ ) a__ : Optional[Any] = self.default_image_processor a__ : Dict = prepare_img() a__ : Optional[int] = image_processor(images=lowerCamelCase__ , return_tensors="pt" ).pixel_values.to(lowerCamelCase__ ) # prepare bool_masked_pos a__ : Optional[Any] = torch.ones((1, 196) , dtype=torch.bool ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): a__ : Any = model(pixel_values=lowerCamelCase__ , bool_masked_pos=lowerCamelCase__ ) a__ : Tuple = outputs.logits # verify the logits a__ : List[str] = torch.Size((1, 196, 8_192) ) self.assertEqual(logits.shape , lowerCamelCase__ ) a__ : Optional[int] = torch.tensor( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , lowerCamelCase__ , atol=1E-2 ) ) @slow def _UpperCamelCase( self : Dict ): a__ : str = BeitForImageClassification.from_pretrained("microsoft/beit-base-patch16-224" ).to(lowerCamelCase__ ) a__ : int = self.default_image_processor a__ : List[Any] = prepare_img() a__ : Tuple = image_processor(images=lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): a__ : Union[str, Any] = model(**lowerCamelCase__ ) a__ : List[str] = outputs.logits # verify the logits a__ : Union[str, Any] = torch.Size((1, 1_000) ) self.assertEqual(logits.shape , lowerCamelCase__ ) a__ : int = torch.tensor([-1.2385, -1.0987, -1.0108] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(logits[0, :3] , lowerCamelCase__ , atol=1E-4 ) ) a__ : Tuple = 281 self.assertEqual(logits.argmax(-1 ).item() , lowerCamelCase__ ) @slow def _UpperCamelCase( self : Any ): a__ : Dict = BeitForImageClassification.from_pretrained("microsoft/beit-large-patch16-224-pt22k-ft22k" ).to( lowerCamelCase__ ) a__ : str = self.default_image_processor a__ : List[str] = prepare_img() a__ : Tuple = image_processor(images=lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): a__ : Dict = model(**lowerCamelCase__ ) a__ : List[str] = outputs.logits # verify the logits a__ : Optional[int] = torch.Size((1, 21_841) ) self.assertEqual(logits.shape , lowerCamelCase__ ) a__ : Optional[Any] = torch.tensor([1.6881, -0.2787, 0.5901] ).to(lowerCamelCase__ ) self.assertTrue(torch.allclose(logits[0, :3] , lowerCamelCase__ , atol=1E-4 ) ) a__ : Optional[Any] = 2_396 self.assertEqual(logits.argmax(-1 ).item() , lowerCamelCase__ ) @slow def _UpperCamelCase( self : int ): a__ : Optional[Any] = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) a__ : Tuple = model.to(lowerCamelCase__ ) a__ : List[Any] = BeitImageProcessor(do_resize=lowerCamelCase__ , size=640 , do_center_crop=lowerCamelCase__ ) a__ : Tuple = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) a__ : Union[str, Any] = Image.open(ds[0]["file"] ) a__ : List[Any] = image_processor(images=lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): a__ : Optional[Any] = model(**lowerCamelCase__ ) a__ : List[str] = outputs.logits # verify the logits a__ : Tuple = torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape , lowerCamelCase__ ) a__ : int = version.parse(PIL.__version__ ) < version.parse("9.0.0" ) if is_pillow_less_than_a: a__ : Dict = torch.tensor( [ [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]], [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]], [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]], ] , device=lowerCamelCase__ , ) else: a__ : Dict = torch.tensor( [ [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]], [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]], [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]], ] , device=lowerCamelCase__ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , lowerCamelCase__ , atol=1E-4 ) ) @slow def _UpperCamelCase( self : Tuple ): a__ : str = BeitForSemanticSegmentation.from_pretrained("microsoft/beit-base-finetuned-ade-640-640" ) a__ : List[Any] = model.to(lowerCamelCase__ ) a__ : int = BeitImageProcessor(do_resize=lowerCamelCase__ , size=640 , do_center_crop=lowerCamelCase__ ) a__ : Optional[int] = load_dataset("hf-internal-testing/fixtures_ade20k" , split="test" ) a__ : str = Image.open(ds[0]["file"] ) a__ : str = image_processor(images=lowerCamelCase__ , return_tensors="pt" ).to(lowerCamelCase__ ) # forward pass with torch.no_grad(): a__ : List[Any] = model(**lowerCamelCase__ ) a__ : Any = outputs.logits.detach().cpu() a__ : List[Any] = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase__ , target_sizes=[(500, 300)] ) a__ : Optional[int] = torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , lowerCamelCase__ ) a__ : List[str] = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase__ ) a__ : Any = torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape , lowerCamelCase__ )
37
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE( A__ ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = '''timm_backbone''' def __init__( self ,SCREAMING_SNAKE_CASE__=None ,SCREAMING_SNAKE_CASE__=3 ,SCREAMING_SNAKE_CASE__=True ,SCREAMING_SNAKE_CASE__=True ,SCREAMING_SNAKE_CASE__=None ,**SCREAMING_SNAKE_CASE__ ,) -> Union[str, Any]: """simple docstring""" super().__init__(**lowerCamelCase__ ) __SCREAMING_SNAKE_CASE :Any = backbone __SCREAMING_SNAKE_CASE :Any = num_channels __SCREAMING_SNAKE_CASE :Union[str, Any] = features_only __SCREAMING_SNAKE_CASE :List[str] = use_pretrained_backbone __SCREAMING_SNAKE_CASE :Optional[Any] = True __SCREAMING_SNAKE_CASE :Optional[int] = out_indices if out_indices is not None else (-1,)
498
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging UpperCamelCase : Dict = logging.get_logger(__name__) def UpperCamelCase_ ( __a ) -> Union[str, Any]: a__ : Tuple = R"\w+[.]\d+" a__ : List[Any] = re.findall(__a , __a ) for pat in pats: a__ : Union[str, Any] = key.replace(__a , "_".join(pat.split("." ) ) ) return key def UpperCamelCase_ ( __a , __a , __a ) -> List[str]: a__ : List[str] = pt_tuple_key[:-1] + ("scale",) if ( any("norm" in str_ for str_ in pt_tuple_key ) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): a__ : Any = pt_tuple_key[:-1] + ("scale",) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: a__ : Optional[Any] = pt_tuple_key[:-1] + ("scale",) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: a__ : Union[str, Any] = pt_tuple_key[:-1] + ("embedding",) return renamed_pt_tuple_key, pt_tensor # conv layer a__ : List[str] = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: a__ : str = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer a__ : Tuple = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight": a__ : Tuple = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight a__ : Optional[Any] = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias a__ : Union[str, Any] = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def UpperCamelCase_ ( __a , __a , __a=42 ) -> str: # Step 1: Convert pytorch tensor to numpy a__ : Optional[int] = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params a__ : Tuple = flax_model.init_weights(PRNGKey(__a ) ) a__ : Optional[Any] = flatten_dict(__a ) a__ : Union[str, Any] = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): a__ : Optional[int] = rename_key(__a ) a__ : Optional[int] = tuple(renamed_pt_key.split("." ) ) # Correctly rename weight parameters a__, a__ : Union[str, Any] = rename_key_and_reshape_tensor(__a , __a , __a ) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape ''' f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.''' ) # also add unexpected weight so that warning is thrown a__ : str = jnp.asarray(__a ) return unflatten_dict(__a )
37
0
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class a ( A__ ): """simple docstring""" def __init__( self , snake_case_ , snake_case_ , snake_case_ = None , snake_case_ = None , snake_case_ = False , **snake_case_ , ): '''simple docstring''' super().__init__(features=lowerCamelCase__ , cache_dir=lowerCamelCase__ , keep_in_memory=lowerCamelCase__ , **lowerCamelCase__ ) __UpperCAmelCase: str = Sql( cache_dir=lowerCamelCase__ , features=lowerCamelCase__ , sql=lowerCamelCase__ , con=lowerCamelCase__ , **lowerCamelCase__ , ) def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Optional[Any] = None __UpperCAmelCase: Dict = None __UpperCAmelCase: Union[str, Any] = None __UpperCAmelCase: Union[str, Any] = None self.builder.download_and_prepare( download_config=lowerCamelCase__ , download_mode=lowerCamelCase__ , verification_mode=lowerCamelCase__ , base_path=lowerCamelCase__ , ) # Build dataset for splits __UpperCAmelCase: List[str] = self.builder.as_dataset( split="""train""" , verification_mode=lowerCamelCase__ , in_memory=self.keep_in_memory ) return dataset class a : """simple docstring""" def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ = None , snake_case_ = None , **snake_case_ , ): '''simple docstring''' if num_proc is not None and num_proc <= 0: raise ValueError(F'''num_proc {num_proc} must be an integer > 0.''' ) __UpperCAmelCase: Any = dataset __UpperCAmelCase: str = name __UpperCAmelCase: Tuple = con __UpperCAmelCase: List[Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE __UpperCAmelCase: Any = num_proc __UpperCAmelCase: Tuple = to_sql_kwargs def lowercase_ ( self ): '''simple docstring''' __UpperCAmelCase: Any = self.to_sql_kwargs.pop("""sql""" , lowerCamelCase__ ) __UpperCAmelCase: int = self.to_sql_kwargs.pop("""con""" , lowerCamelCase__ ) __UpperCAmelCase: int = self.to_sql_kwargs.pop("""index""" , lowerCamelCase__ ) __UpperCAmelCase: int = self._write(index=lowerCamelCase__ , **self.to_sql_kwargs ) return written def lowercase_ ( self , snake_case_ ): '''simple docstring''' __UpperCAmelCase: Union[str, Any] = args __UpperCAmelCase: Any = {**to_sql_kwargs, "if_exists": "append"} if offset > 0 else to_sql_kwargs __UpperCAmelCase: Tuple = query_table( table=self.dataset.data , key=slice(lowerCamelCase__ , offset + self.batch_size ) , indices=self.dataset._indices , ) __UpperCAmelCase: str = batch.to_pandas() __UpperCAmelCase: List[Any] = df.to_sql(self.name , self.con , index=lowerCamelCase__ , **lowerCamelCase__ ) return num_rows or len(lowerCamelCase__ ) def lowercase_ ( self , snake_case_ , **snake_case_ ): '''simple docstring''' __UpperCAmelCase: str = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: __UpperCAmelCase: List[str] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , lowerCamelCase__ , lowerCamelCase__ )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
523
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments def UpperCamelCase_ ( ) -> int: a__ : Any = HfArgumentParser(__a ) a__ : Any = parser.parse_args_into_dataclasses()[0] a__ : Optional[int] = TensorFlowBenchmark(args=__a ) try: a__ : Optional[int] = parser.parse_args_into_dataclasses()[0] except ValueError as e: a__ : Tuple = "Arg --no_{0} is no longer used, please use --no-{0} instead." a__ : List[Any] = " ".join(str(__a ).split(" " )[:-1] ) a__ : str = "" a__ : List[Any] = eval(str(__a ).split(" " )[-1] ) a__ : List[str] = [] for arg in depreciated_args: # arg[2:] removes '--' if arg[2:] in TensorFlowBenchmark.deprecated_args: # arg[5:] removes '--no_' full_error_msg += arg_error_msg.format(arg[5:] ) else: wrong_args.append(__a ) if len(__a ) > 0: a__ : Tuple = full_error_msg + begin_error_msg + str(__a ) raise ValueError(__a ) benchmark.run() if __name__ == "__main__": main()
37
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __lowerCAmelCase : Tuple = logging.get_logger(__name__) __lowerCAmelCase : str = { """xlm-mlm-en-2048""": """https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json""", """xlm-mlm-ende-1024""": """https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json""", """xlm-mlm-enfr-1024""": """https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json""", """xlm-mlm-enro-1024""": """https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json""", """xlm-mlm-tlm-xnli15-1024""": """https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json""", """xlm-mlm-xnli15-1024""": """https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json""", """xlm-clm-enfr-1024""": """https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json""", """xlm-clm-ende-1024""": """https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json""", """xlm-mlm-17-1280""": """https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json""", """xlm-mlm-100-1280""": """https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json""", } class A ( A__ ): a_ = '''xlm''' a_ = { '''hidden_size''': '''emb_dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', '''n_words''': '''vocab_size''', # For backward compatibility } def __init__( self : Tuple , __a : List[Any]=3_0_1_4_5 , __a : Any=2_0_4_8 , __a : int=1_2 , __a : Dict=1_6 , __a : Optional[int]=0.1 , __a : Any=0.1 , __a : Union[str, Any]=True , __a : Dict=False , __a : Optional[int]=False , __a : List[Any]=False , __a : List[str]=1 , __a : str=True , __a : str=5_1_2 , __a : List[str]=2_0_4_8**-0.5 , __a : List[str]=1e-12 , __a : Any=0.0_2 , __a : Tuple=0 , __a : Any=1 , __a : Optional[Any]=2 , __a : Optional[Any]=3 , __a : Optional[Any]=5 , __a : Tuple=True , __a : Optional[Any]="first" , __a : Optional[int]=True , __a : Tuple=None , __a : int=True , __a : Dict=0.1 , __a : Tuple=5 , __a : Any=5 , __a : List[Any]=0 , __a : Optional[int]=0 , __a : Optional[Any]=2 , __a : Tuple=0 , **__a : List[str] , ) -> List[str]: __UpperCAmelCase = vocab_size __UpperCAmelCase = emb_dim __UpperCAmelCase = n_layers __UpperCAmelCase = n_heads __UpperCAmelCase = dropout __UpperCAmelCase = attention_dropout __UpperCAmelCase = gelu_activation __UpperCAmelCase = sinusoidal_embeddings __UpperCAmelCase = causal __UpperCAmelCase = asm __UpperCAmelCase = n_langs __UpperCAmelCase = use_lang_emb __UpperCAmelCase = layer_norm_eps __UpperCAmelCase = bos_index __UpperCAmelCase = eos_index __UpperCAmelCase = pad_index __UpperCAmelCase = unk_index __UpperCAmelCase = mask_index __UpperCAmelCase = is_encoder __UpperCAmelCase = max_position_embeddings __UpperCAmelCase = embed_init_std __UpperCAmelCase = init_std __UpperCAmelCase = summary_type __UpperCAmelCase = summary_use_proj __UpperCAmelCase = summary_activation __UpperCAmelCase = summary_proj_to_labels __UpperCAmelCase = summary_first_dropout __UpperCAmelCase = start_n_top __UpperCAmelCase = end_n_top __UpperCAmelCase = mask_token_id __UpperCAmelCase = lang_id if "n_words" in kwargs: __UpperCAmelCase = kwargs["n_words"] super().__init__(pad_token_id=lowerCamelCase__ , bos_token_id=lowerCamelCase__ , **lowerCamelCase__ ) class A ( A__ ): @property def snake_case__ ( self : Dict ) -> Dict: if self.task == "multiple-choice": __UpperCAmelCase = {0: "batch", 1: "choice", 2: "sequence"} else: __UpperCAmelCase = {0: "batch", 1: "sequence"} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
262
import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip UpperCamelCase : Optional[int] = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def UpperCamelCase_ ( __a ) -> Any: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def UpperCamelCase_ ( __a , __a , __a ) -> Any: return max(metric_fn(__a , __a ) for gt in ground_truths ) def UpperCamelCase_ ( __a , __a , __a ) -> List[str]: a__ : Tuple = [line.strip() for line in open(__a , "r" ).readlines()] a__ : Tuple = [] if args.gold_data_mode == "qa": a__ : Any = pd.read_csv(__a , sep="\t" , header=__a ) for answer_list in data[1]: a__ : Union[str, Any] = ast.literal_eval(__a ) answers.append(__a ) else: a__ : List[str] = [line.strip() for line in open(__a , "r" ).readlines()] a__ : List[str] = [[reference] for reference in references] a__ : List[str] = 0 for prediction, ground_truths in zip(__a , __a ): total += 1 em += metric_max_over_ground_truths(__a , __a , __a ) fa += metric_max_over_ground_truths(__a , __a , __a ) a__ : Dict = 100.0 * em / total a__ : Optional[Any] = 100.0 * fa / total logger.info(f'''F1: {fa:.2f}''' ) logger.info(f'''EM: {em:.2f}''' ) def UpperCamelCase_ ( __a , __a , __a ) -> Optional[Any]: a__ : Optional[Any] = args.k a__ : str = [line.strip() for line in open(__a , "r" ).readlines()] a__ : Tuple = [line.strip() for line in open(__a , "r" ).readlines()] a__ : Tuple = 0 for hypo, reference in zip(__a , __a ): a__ : Any = set(hypo.split("\t" )[:k] ) a__ : Union[str, Any] = set(reference.split("\t" ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k a__ : Union[str, Any] = 100.0 * em / total logger.info(f'''Precision@{k}: {em: .2f}''' ) def UpperCamelCase_ ( __a , __a , __a ) -> Optional[Any]: def strip_title(__a ): if title.startswith("\"" ): a__ : Optional[Any] = title[1:] if title.endswith("\"" ): a__ : Union[str, Any] = title[:-1] return title a__ : Optional[int] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __a , return_tensors="pt" , padding=__a , truncation=__a , )["input_ids"].to(args.device ) a__ : Optional[int] = rag_model.rag.question_encoder(__a ) a__ : Union[str, Any] = question_enc_outputs[0] a__ : Optional[int] = rag_model.retriever( __a , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="pt" , ) a__ : List[Any] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) a__ : int = [] for docs in all_docs: a__ : Optional[int] = [strip_title(__a ) for title in docs["title"]] provenance_strings.append("\t".join(__a ) ) return provenance_strings def UpperCamelCase_ ( __a , __a , __a ) -> Dict: with torch.no_grad(): a__ : Optional[int] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( __a , return_tensors="pt" , padding=__a , truncation=__a ) a__ : Any = inputs_dict.input_ids.to(args.device ) a__ : Dict = inputs_dict.attention_mask.to(args.device ) a__ : Optional[int] = rag_model.generate( # rag_model overwrites generate __a , attention_mask=__a , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=__a , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) a__ : int = rag_model.retriever.generator_tokenizer.batch_decode(__a , skip_special_tokens=__a ) if args.print_predictions: for q, a in zip(__a , __a ): logger.info("Q: {} - A: {}".format(__a , __a ) ) return answers def UpperCamelCase_ ( ) -> List[str]: a__ : int = argparse.ArgumentParser() parser.add_argument( "--model_type" , choices=["rag_sequence", "rag_token", "bart"] , type=__a , help=( "RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the" " model_name_or_path" ) , ) parser.add_argument( "--index_name" , default=__a , choices=["exact", "compressed", "legacy"] , type=__a , help="RAG model retriever type" , ) parser.add_argument( "--index_path" , default=__a , type=__a , help="Path to the retrieval index" , ) parser.add_argument("--n_docs" , default=5 , type=__a , help="Number of retrieved docs" ) parser.add_argument( "--model_name_or_path" , default=__a , type=__a , required=__a , help="Path to pretrained checkpoints or model identifier from huggingface.co/models" , ) parser.add_argument( "--eval_mode" , choices=["e2e", "retrieval"] , default="e2e" , type=__a , help=( "Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates" " precision@k." ) , ) parser.add_argument("--k" , default=1 , type=__a , help="k for the precision@k calculation" ) parser.add_argument( "--evaluation_set" , default=__a , type=__a , required=__a , help="Path to a file containing evaluation samples" , ) parser.add_argument( "--gold_data_path" , default=__a , type=__a , required=__a , help="Path to a tab-separated file with gold samples" , ) parser.add_argument( "--gold_data_mode" , default="qa" , type=__a , choices=["qa", "ans"] , help=( "Format of the gold data file" "qa - a single line in the following format: question [tab] answer_list" "ans - a single line of the gold file contains the expected answer string" ) , ) parser.add_argument( "--predictions_path" , type=__a , default="predictions.txt" , help="Name of the predictions file, to be stored in the checkpoints directory" , ) parser.add_argument( "--eval_all_checkpoints" , action="store_true" , help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number" , ) parser.add_argument( "--eval_batch_size" , default=8 , type=__a , help="Batch size per GPU/CPU for evaluation." , ) parser.add_argument( "--recalculate" , help="Recalculate predictions even if the prediction file exists" , action="store_true" , ) parser.add_argument( "--num_beams" , default=4 , type=__a , help="Number of beams to be used when generating answers" , ) parser.add_argument("--min_length" , default=1 , type=__a , help="Min length of the generated answers" ) parser.add_argument("--max_length" , default=50 , type=__a , help="Max length of the generated answers" ) parser.add_argument( "--print_predictions" , action="store_true" , help="If True, prints predictions while evaluating." , ) parser.add_argument( "--print_docs" , action="store_true" , help="If True, prints docs retried while generating." , ) a__ : int = parser.parse_args() a__ : Dict = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) return args def UpperCamelCase_ ( __a ) -> Optional[int]: a__ : Tuple = {} if args.model_type is None: a__ : List[str] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith("rag" ): a__ : int = RagTokenForGeneration if args.model_type == "rag_token" else RagSequenceForGeneration a__ : Tuple = args.n_docs if args.index_name is not None: a__ : Any = args.index_name if args.index_path is not None: a__ : int = args.index_path else: a__ : Optional[Any] = BartForConditionalGeneration a__ : Tuple = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info("Evaluate the following checkpoints: %s" , __a ) a__ : Any = get_scores if args.eval_mode == "e2e" else get_precision_at_k a__ : Union[str, Any] = evaluate_batch_eae if args.eval_mode == "e2e" else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info("Calculating metrics based on an existing predictions file: {}".format(args.predictions_path ) ) score_fn(__a , args.predictions_path , args.gold_data_path ) continue logger.info("***** Running evaluation for {} *****".format(__a ) ) logger.info(" Batch size = %d" , args.eval_batch_size ) logger.info(" Predictions will be stored under {}".format(args.predictions_path ) ) if args.model_type.startswith("rag" ): a__ : str = RagRetriever.from_pretrained(__a , **__a ) a__ : Optional[int] = model_class.from_pretrained(__a , retriever=__a , **__a ) model.retriever.init_retrieval() else: a__ : Dict = model_class.from_pretrained(__a , **__a ) model.to(args.device ) with open(args.evaluation_set , "r" ) as eval_file, open(args.predictions_path , "w" ) as preds_file: a__ : List[Any] = [] for line in tqdm(__a ): questions.append(line.strip() ) if len(__a ) == args.eval_batch_size: a__ : Union[str, Any] = evaluate_batch_fn(__a , __a , __a ) preds_file.write("\n".join(__a ) + "\n" ) preds_file.flush() a__ : Any = [] if len(__a ) > 0: a__ : List[str] = evaluate_batch_fn(__a , __a , __a ) preds_file.write("\n".join(__a ) ) preds_file.flush() score_fn(__a , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": UpperCamelCase : List[Any] = get_args() main(args)
37
0
'''simple docstring''' import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=os.environ.get("LOGLEVEL", "INFO").upper(), stream=sys.stdout, ) UpperCamelCase =logging.getLogger(__name__) UpperCamelCase ={"""facebook/bart-base""": BartForConditionalGeneration} UpperCamelCase ={"""facebook/bart-base""": BartTokenizer} def snake_case ( ) -> Optional[Any]: """simple docstring""" UpperCamelCase_ : Optional[Any] = argparse.ArgumentParser(description="""Export Bart model + Beam Search to ONNX graph.""" ) parser.add_argument( """--validation_file""" , type=__a , default=__a , help="""A csv or a json file containing the validation data.""" ) parser.add_argument( """--max_length""" , type=__a , default=5 , help="""The maximum total input sequence length after tokenization.""" , ) parser.add_argument( """--num_beams""" , type=__a , default=__a , help=( """Number of beams to use for evaluation. This argument will be """ """passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.""" ) , ) parser.add_argument( """--model_name_or_path""" , type=__a , help="""Path to pretrained model or model identifier from huggingface.co/models.""" , required=__a , ) parser.add_argument( """--config_name""" , type=__a , default=__a , help="""Pretrained config name or path if not the same as model_name""" , ) parser.add_argument( """--device""" , type=__a , default="""cpu""" , help="""Device where the model will be run""" , ) parser.add_argument("""--output_file_path""" , type=__a , default=__a , help="""Where to store the final ONNX file.""" ) UpperCamelCase_ : str = parser.parse_args() return args def snake_case ( a_ : List[Any] , a_ : Union[str, Any]="cpu" ) -> List[Any]: """simple docstring""" UpperCamelCase_ : Any = model_dict[model_name].from_pretrained(__a ).to(__a ) UpperCamelCase_ : List[str] = tokenizer_dict[model_name].from_pretrained(__a ) if model_name in ["facebook/bart-base"]: UpperCamelCase_ : Optional[int] = 0 UpperCamelCase_ : Union[str, Any] = None UpperCamelCase_ : Union[str, Any] = 0 return huggingface_model, tokenizer def snake_case ( a_ : Optional[int] , a_ : Optional[Any] , a_ : List[str] , a_ : List[str] , a_ : str ) -> Union[str, Any]: """simple docstring""" model.eval() UpperCamelCase_ : int = None UpperCamelCase_ : str = torch.jit.script(BARTBeamSearchGenerator(__a ) ) with torch.no_grad(): UpperCamelCase_ : int = "My friends are cool but they eat too many carbs." UpperCamelCase_ : str = tokenizer([ARTICLE_TO_SUMMARIZE] , max_length=1_024 , return_tensors="""pt""" ).to(model.device ) UpperCamelCase_ : int = model.generate( inputs["""input_ids"""] , attention_mask=inputs["""attention_mask"""] , num_beams=__a , max_length=__a , early_stopping=__a , decoder_start_token_id=model.config.decoder_start_token_id , ) torch.onnx.export( __a , ( inputs["""input_ids"""], inputs["""attention_mask"""], num_beams, max_length, model.config.decoder_start_token_id, ) , __a , opset_version=14 , input_names=["""input_ids""", """attention_mask""", """num_beams""", """max_length""", """decoder_start_token_id"""] , output_names=["""output_ids"""] , dynamic_axes={ """input_ids""": {0: """batch""", 1: """seq"""}, """output_ids""": {0: """batch""", 1: """seq_out"""}, } , example_outputs=__a , ) logger.info("""Model exported to {}""".format(__a ) ) UpperCamelCase_ : List[str] = remove_dup_initializers(os.path.abspath(__a ) ) logger.info("""Deduplicated and optimized model written to {}""".format(__a ) ) UpperCamelCase_ : Dict = onnxruntime.InferenceSession(__a ) UpperCamelCase_ : Tuple = ort_sess.run( __a , { """input_ids""": inputs["""input_ids"""].cpu().numpy(), """attention_mask""": inputs["""attention_mask"""].cpu().numpy(), """num_beams""": np.array(__a ), """max_length""": np.array(__a ), """decoder_start_token_id""": np.array(model.config.decoder_start_token_id ), } , ) np.testing.assert_allclose(summary_ids.cpu().numpy() , ort_out[0] , rtol=1e-3 , atol=1e-3 ) logger.info("""Model outputs from torch and ONNX Runtime are similar.""" ) logger.info("""Success.""" ) def snake_case ( ) -> Tuple: """simple docstring""" UpperCamelCase_ : int = parse_args() UpperCamelCase_ : str = 5 UpperCamelCase_ : str = 4 # 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 , ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() UpperCamelCase_ : Optional[int] = torch.device(args.device ) UpperCamelCase_ : int = load_model_tokenizer(args.model_name_or_path , __a ) if model.config.decoder_start_token_id is None: raise ValueError("""Make sure that `config.decoder_start_token_id` is correctly defined""" ) model.to(__a ) if args.max_length: UpperCamelCase_ : Optional[int] = args.max_length if args.num_beams: UpperCamelCase_ : int = args.num_beams if args.output_file_path: UpperCamelCase_ : str = args.output_file_path else: UpperCamelCase_ : Optional[Any] = "BART.onnx" logger.info("""Exporting model to ONNX""" ) export_and_validate_model(__a , __a , __a , __a , __a ) if __name__ == "__main__": main()
208
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def UpperCamelCase_ ( __a , __a , __a , __a , __a , __a = None , ) -> str: a__ : int = {} if train_file is not None: a__ : int = [train_file] if eval_file is not None: a__ : Union[str, Any] = [eval_file] if test_file is not None: a__ : str = [test_file] a__ : Optional[Any] = datasets.load_dataset("csv" , data_files=__a ) a__ : List[Any] = list(ds[list(files.keys() )[0]].features.keys() ) a__ : str = features_name.pop(__a ) a__ : Dict = list(set(ds[list(files.keys() )[0]][label_name] ) ) a__ : str = {label: i for i, label in enumerate(__a )} a__ : Tuple = tokenizer.model_input_names a__ : List[str] = {} if len(__a ) == 1: for k in files.keys(): a__ : Optional[Any] = ds[k].map( lambda __a : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=__a , max_length=__a , padding="max_length" ) , batched=__a , ) elif len(__a ) == 2: for k in files.keys(): a__ : Dict = ds[k].map( lambda __a : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=__a , max_length=__a , padding="max_length" , ) , batched=__a , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: a__ : str = {k: v for k, v in ex.items() if k in input_names} a__ : str = labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: a__ : Tuple = {k: v for k, v in ex.items() if k in input_names} a__ : List[Any] = labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: a__ : List[Any] = {k: v for k, v in ex.items() if k in input_names} a__ : Optional[int] = labelaid[ex[label_name]] yield (d, label) a__ : Optional[Any] = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: a__ : Optional[int] = train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) a__ : Union[str, Any] = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: a__ : Optional[Any] = val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) a__ : Union[str, Any] = ( tf.data.Dataset.from_generator( __a , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: a__ : Tuple = test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid UpperCamelCase : Optional[Any] = logging.getLogger(__name__) @dataclass class A__ : """simple docstring""" _lowercase = field(metadata={'help': 'Which column contains the label'} ) _lowercase = field(default=A__ , metadata={'help': 'The path of the training file'} ) _lowercase = field(default=A__ , metadata={'help': 'The path of the development file'} ) _lowercase = field(default=A__ , metadata={'help': 'The path of the test file'} ) _lowercase = field( default=1_2_8 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) _lowercase = field( default=A__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) @dataclass class A__ : """simple docstring""" _lowercase = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) _lowercase = field( default=A__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) _lowercase = field( default=A__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) _lowercase = field(default=A__ , metadata={'help': 'Set this flag to use fast tokenization.'} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. _lowercase = field( default=A__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) def UpperCamelCase_ ( ) -> Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. a__ : str = HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) a__, a__, a__ : str = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use''' " --overwrite_output_dir to overcome." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.info( f'''n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, ''' f'''16-bits training: {training_args.fpaa}''' ) logger.info(f'''Training/evaluation parameters {training_args}''' ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. a__ : Union[str, Any] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) a__, a__, a__, a__ : Optional[Any] = get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=__a , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) a__ : Optional[int] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(__a ) , labelaid=__a , idalabel={id: label for label, id in labelaid.items()} , finetuning_task="text-classification" , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): a__ : Any = TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool(".bin" in model_args.model_name_or_path ) , config=__a , cache_dir=model_args.cache_dir , ) def compute_metrics(__a ) -> Dict: a__ : Union[str, Any] = np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer a__ : Dict = TFTrainer( model=__a , args=__a , train_dataset=__a , eval_dataset=__a , compute_metrics=__a , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation a__ : Optional[Any] = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) a__ : Dict = trainer.evaluate() a__ : int = os.path.join(training_args.output_dir , "eval_results.txt" ) with open(__a , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(f''' {key} = {value}''' ) writer.write(f'''{key} = {value}\n''' ) results.update(__a ) return results if __name__ == "__main__": main()
37
0
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a__ ( A__ , unittest.TestCase ): _A = CLIPTokenizer _A = CLIPTokenizerFast _A = True _A = {} _A = False def lowerCAmelCase ( self : List[Any] ) -> Any: """simple docstring""" super().setUp() # fmt: off lowerCamelCase_: Any = ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: on lowerCamelCase_: Optional[Any] = dict(zip(lowerCamelCase__ , range(len(lowerCamelCase__ ) ) ) ) lowerCamelCase_: Optional[Any] = ["#version: 0.2", "l o", "lo w</w>", "e r</w>"] lowerCamelCase_: Optional[Any] = {"unk_token": "<unk>"} lowerCamelCase_: int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) lowerCamelCase_: int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(lowerCamelCase__ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(lowerCamelCase__ ) ) def lowerCAmelCase ( self : Dict , **A_ : int ) -> Union[str, Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase__ ) def lowerCAmelCase ( self : Union[str, Any] , **A_ : Optional[int] ) -> Optional[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowerCamelCase__ ) def lowerCAmelCase ( self : Dict , A_ : Optional[Any] ) -> Tuple: """simple docstring""" lowerCamelCase_: int = "lower newer" lowerCamelCase_: Optional[int] = "lower newer" return input_text, output_text def lowerCAmelCase ( self : List[str] ) -> List[Any]: """simple docstring""" lowerCamelCase_: Union[str, Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCamelCase_: int = "lower newer" lowerCamelCase_: List[str] = ["lo", "w", "er</w>", "n", "e", "w", "er</w>"] lowerCamelCase_: Union[str, Any] = tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) lowerCamelCase_: int = tokens + [tokenizer.unk_token] lowerCamelCase_: Union[str, Any] = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase__ ) , lowerCamelCase__ ) @require_ftfy def lowerCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCamelCase_: List[str] = self.tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ ) lowerCamelCase_: Any = self.rust_tokenizer_class.from_pretrained(lowerCamelCase__ , **lowerCamelCase__ ) lowerCamelCase_: int = "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d." lowerCamelCase_: Optional[Any] = tokenizer_s.tokenize(lowerCamelCase__ ) lowerCamelCase_: Dict = tokenizer_r.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways lowerCamelCase_: Optional[Any] = "xa\u0303y" + " " + "x\xe3y" lowerCamelCase_: Optional[int] = tokenizer_s.tokenize(lowerCamelCase__ ) lowerCamelCase_: int = tokenizer_r.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) # Test that the tokenization is identical on unicode of space type lowerCamelCase_: str = [ "\u0009", # (horizontal tab, '\t') "\u000B", # (vertical tab) "\u000C", # (form feed) "\u0020", # (space, ' ') "\u200E", # (left-to-right mark):w "\u200F", # (right-to-left mark) ] for unicode_seq in spaces_unicodes: lowerCamelCase_: Any = tokenizer_s.tokenize(lowerCamelCase__ ) lowerCamelCase_: int = tokenizer_r.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) # Test that the tokenization is identical on unicode of line break type lowerCamelCase_: Union[str, Any] = [ "\u000A", # (line feed, '\n') "\r\n", # (carriage return and line feed, '\r\n') "\u000D", # (carriage return, '\r') "\r", # (carriage return, '\r') "\u000D", # (carriage return, '\r') "\u2028", # (line separator) "\u2029", # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: lowerCamelCase_: List[Any] = tokenizer_s.tokenize(lowerCamelCase__ ) lowerCamelCase_: int = tokenizer_r.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) def lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCamelCase_: str = "hello" # `hello` is a token in the vocabulary of `pretrained_name` lowerCamelCase_: Tuple = f"""{text_of_1_token} {text_of_1_token}""" lowerCamelCase_: Optional[int] = self.rust_tokenizer_class.from_pretrained( lowerCamelCase__ , use_fast=lowerCamelCase__ , ) lowerCamelCase_: Union[str, Any] = tokenizer_r(lowerCamelCase__ , return_offsets_mapping=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (0, len(lowerCamelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (len(lowerCamelCase__ ) + 1, len(lowerCamelCase__ ) + 1 + len(lowerCamelCase__ )) , ) lowerCamelCase_: Optional[Any] = f""" {text}""" lowerCamelCase_: str = self.rust_tokenizer_class.from_pretrained( lowerCamelCase__ , use_fast=lowerCamelCase__ , ) lowerCamelCase_: Dict = tokenizer_r(lowerCamelCase__ , return_offsets_mapping=lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(lowerCamelCase__ )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(lowerCamelCase__ ) + 1, 1 + len(lowerCamelCase__ ) + 1 + len(lowerCamelCase__ )) , ) def lowerCAmelCase ( self : int ) -> int: """simple docstring""" # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(lowerCamelCase__ ) as context: self.rust_tokenizer_class.from_pretrained("""robot-test/old-clip-tokenizer""" ) self.assertTrue( context.exception.args[0].startswith( """The `backend_tokenizer` provided does not match the expected format.""" ) ) @require_ftfy def lowerCAmelCase ( self : int ) -> Dict: """simple docstring""" super().test_tokenization_python_rust_equals() def lowerCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" # CLIP always lower cases letters pass
423
import argparse import collections import json import os import re import string import sys import numpy as np UpperCamelCase : List[str] = re.compile(r"""\b(a|an|the)\b""", re.UNICODE) UpperCamelCase : Union[str, Any] = None def UpperCamelCase_ ( ) -> List[str]: a__ : List[Any] = argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0." ) parser.add_argument("data_file" , metavar="data.json" , help="Input data JSON file." ) parser.add_argument("pred_file" , metavar="pred.json" , help="Model predictions." ) parser.add_argument( "--out-file" , "-o" , metavar="eval.json" , help="Write accuracy metrics to file (default is stdout)." ) parser.add_argument( "--na-prob-file" , "-n" , metavar="na_prob.json" , help="Model estimates of probability of no answer." ) parser.add_argument( "--na-prob-thresh" , "-t" , type=__a , default=1.0 , help="Predict \"\" if no-answer probability exceeds this (default = 1.0)." , ) parser.add_argument( "--out-image-dir" , "-p" , metavar="out_images" , default=__a , help="Save precision-recall curves to directory." ) parser.add_argument("--verbose" , "-v" , action="store_true" ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def UpperCamelCase_ ( __a ) -> str: a__ : Optional[Any] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: a__ : Dict = bool(qa["answers"]["text"] ) return qid_to_has_ans def UpperCamelCase_ ( __a ) -> List[Any]: def remove_articles(__a ): return ARTICLES_REGEX.sub(" " , __a ) def white_space_fix(__a ): return " ".join(text.split() ) def remove_punc(__a ): a__ : Union[str, Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__a ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__a ) ) ) ) def UpperCamelCase_ ( __a ) -> Dict: if not s: return [] return normalize_answer(__a ).split() def UpperCamelCase_ ( __a , __a ) -> str: return int(normalize_answer(__a ) == normalize_answer(__a ) ) def UpperCamelCase_ ( __a , __a ) -> Dict: a__ : int = get_tokens(__a ) a__ : Optional[Any] = get_tokens(__a ) a__ : Any = collections.Counter(__a ) & collections.Counter(__a ) a__ : Dict = sum(common.values() ) if len(__a ) == 0 or len(__a ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 a__ : Tuple = 1.0 * num_same / len(__a ) a__ : str = 1.0 * num_same / len(__a ) a__ : str = (2 * precision * recall) / (precision + recall) return fa def UpperCamelCase_ ( __a , __a ) -> int: a__ : List[str] = {} a__ : Optional[int] = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: a__ : List[Any] = qa["id"] a__ : Dict = [t for t in qa["answers"]["text"] if normalize_answer(__a )] if not gold_answers: # For unanswerable questions, only correct answer is empty string a__ : Tuple = [""] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue a__ : Tuple = preds[qid] # Take max over all gold answers a__ : Optional[int] = max(compute_exact(__a , __a ) for a in gold_answers ) a__ : str = max(compute_fa(__a , __a ) for a in gold_answers ) return exact_scores, fa_scores def UpperCamelCase_ ( __a , __a , __a , __a ) -> Optional[int]: a__ : Optional[Any] = {} for qid, s in scores.items(): a__ : Dict = na_probs[qid] > na_prob_thresh if pred_na: a__ : Dict = float(not qid_to_has_ans[qid] ) else: a__ : Optional[Any] = s return new_scores def UpperCamelCase_ ( __a , __a , __a=None ) -> Tuple: if not qid_list: a__ : Union[str, Any] = len(__a ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores.values() ) / total), ("f1", 100.0 * sum(fa_scores.values() ) / total), ("total", total), ] ) else: a__ : int = len(__a ) return collections.OrderedDict( [ ("exact", 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ("f1", 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ("total", total), ] ) def UpperCamelCase_ ( __a , __a , __a ) -> List[str]: for k in new_eval: a__ : Optional[Any] = new_eval[k] def UpperCamelCase_ ( __a , __a , __a , __a ) -> Optional[int]: plt.step(__a , __a , color="b" , alpha=0.2 , where="post" ) plt.fill_between(__a , __a , step="post" , alpha=0.2 , color="b" ) plt.xlabel("Recall" ) plt.ylabel("Precision" ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__a ) plt.savefig(__a ) plt.clf() def UpperCamelCase_ ( __a , __a , __a , __a , __a=None , __a=None ) -> Dict: a__ : Optional[Any] = sorted(__a , key=lambda __a : na_probs[k] ) a__ : Any = 0.0 a__ : Optional[int] = 1.0 a__ : Optional[int] = 0.0 a__ : Any = [1.0] a__ : Tuple = [0.0] a__ : List[str] = 0.0 for i, qid in enumerate(__a ): if qid_to_has_ans[qid]: true_pos += scores[qid] a__ : Any = true_pos / float(i + 1 ) a__ : int = true_pos / float(__a ) if i == len(__a ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__a ) recalls.append(__a ) if out_image: plot_pr_curve(__a , __a , __a , __a ) return {"ap": 100.0 * avg_prec} def UpperCamelCase_ ( __a , __a , __a , __a , __a , __a ) -> str: if out_image_dir and not os.path.exists(__a ): os.makedirs(__a ) a__ : Optional[int] = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return a__ : Optional[int] = make_precision_recall_eval( __a , __a , __a , __a , out_image=os.path.join(__a , "pr_exact.png" ) , title="Precision-Recall curve for Exact Match score" , ) a__ : Optional[Any] = make_precision_recall_eval( __a , __a , __a , __a , out_image=os.path.join(__a , "pr_f1.png" ) , title="Precision-Recall curve for F1 score" , ) a__ : str = {k: float(__a ) for k, v in qid_to_has_ans.items()} a__ : Optional[Any] = make_precision_recall_eval( __a , __a , __a , __a , out_image=os.path.join(__a , "pr_oracle.png" ) , title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)" , ) merge_eval(__a , __a , "pr_exact" ) merge_eval(__a , __a , "pr_f1" ) merge_eval(__a , __a , "pr_oracle" ) def UpperCamelCase_ ( __a , __a , __a , __a ) -> str: if not qid_list: return a__ : Optional[Any] = [na_probs[k] for k in qid_list] a__ : str = np.ones_like(__a ) / float(len(__a ) ) plt.hist(__a , weights=__a , bins=20 , range=(0.0, 1.0) ) plt.xlabel("Model probability of no-answer" ) plt.ylabel("Proportion of dataset" ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__a , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def UpperCamelCase_ ( __a , __a , __a , __a ) -> Optional[Any]: a__ : str = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) a__ : Optional[Any] = num_no_ans a__ : Dict = cur_score a__ : Any = 0.0 a__ : Optional[Any] = sorted(__a , key=lambda __a : na_probs[k] ) for i, qid in enumerate(__a ): if qid not in scores: continue if qid_to_has_ans[qid]: a__ : Optional[int] = scores[qid] else: if preds[qid]: a__ : str = -1 else: a__ : Union[str, Any] = 0 cur_score += diff if cur_score > best_score: a__ : Any = cur_score a__ : Dict = na_probs[qid] return 100.0 * best_score / len(__a ), best_thresh def UpperCamelCase_ ( __a , __a , __a , __a , __a , __a ) -> Any: a__, a__ : Tuple = find_best_thresh(__a , __a , __a , __a ) a__, a__ : Tuple = find_best_thresh(__a , __a , __a , __a ) a__ : Any = best_exact a__ : Any = exact_thresh a__ : List[Any] = best_fa a__ : Optional[int] = fa_thresh def UpperCamelCase_ ( ) -> Tuple: with open(OPTS.data_file ) as f: a__ : List[Any] = json.load(__a ) a__ : Any = dataset_json["data"] with open(OPTS.pred_file ) as f: a__ : int = json.load(__a ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: a__ : List[str] = json.load(__a ) else: a__ : Optional[int] = {k: 0.0 for k in preds} a__ : Optional[Any] = make_qid_to_has_ans(__a ) # maps qid to True/False a__ : List[Any] = [k for k, v in qid_to_has_ans.items() if v] a__ : Union[str, Any] = [k for k, v in qid_to_has_ans.items() if not v] a__, a__ : str = get_raw_scores(__a , __a ) a__ : str = apply_no_ans_threshold(__a , __a , __a , OPTS.na_prob_thresh ) a__ : str = apply_no_ans_threshold(__a , __a , __a , OPTS.na_prob_thresh ) a__ : Tuple = make_eval_dict(__a , __a ) if has_ans_qids: a__ : str = make_eval_dict(__a , __a , qid_list=__a ) merge_eval(__a , __a , "HasAns" ) if no_ans_qids: a__ : List[Any] = make_eval_dict(__a , __a , qid_list=__a ) merge_eval(__a , __a , "NoAns" ) if OPTS.na_prob_file: find_all_best_thresh(__a , __a , __a , __a , __a , __a ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__a , __a , __a , __a , __a , OPTS.out_image_dir ) histogram_na_prob(__a , __a , OPTS.out_image_dir , "hasAns" ) histogram_na_prob(__a , __a , OPTS.out_image_dir , "noAns" ) if OPTS.out_file: with open(OPTS.out_file , "w" ) as f: json.dump(__a , __a ) else: print(json.dumps(__a , indent=2 ) ) if __name__ == "__main__": UpperCamelCase : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("""Agg""") import matplotlib.pyplot as plt main()
37
0
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : str ) -> bool: '''simple docstring''' snake_case__ : Union[str, Any] = get_failure_array(__magic_name__ ) # 2) Step through text searching for pattern snake_case__ , snake_case__ : List[str] = 0, 0 # index into text, pattern while i < len(__magic_name__ ): if pattern[j] == text[i]: if j == (len(__magic_name__ ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: snake_case__ : Dict = failure[j - 1] continue i += 1 return False def UpperCamelCase__ ( __magic_name__ : str ) -> list[int]: '''simple docstring''' snake_case__ : Union[str, Any] = [0] snake_case__ : int = 0 snake_case__ : Any = 1 while j < len(__magic_name__ ): if pattern[i] == pattern[j]: i += 1 elif i > 0: snake_case__ : List[str] = failure[i - 1] continue j += 1 failure.append(__magic_name__ ) return failure if __name__ == "__main__": # Test 1) A_ : Optional[Any] = "abc1abc12" A_ : List[str] = "alskfjaldsabc1abc1abc12k23adsfabcabc" A_ : Union[str, Any] = "alskfjaldsk23adsfabcabc" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) A_ : Dict = "ABABX" A_ : int = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) A_ : List[Any] = "AAAB" A_ : List[str] = "ABAAAAAB" assert kmp(pattern, text) # Test 4) A_ : Optional[int] = "abcdabcy" A_ : List[str] = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) A_ : Tuple = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
38
'''simple docstring''' import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[int] = logging.get_logger(__name__) A_ : Tuple = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''segformer''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=[2, 2, 2, 2] , __SCREAMING_SNAKE_CASE=[8, 4, 2, 1] , __SCREAMING_SNAKE_CASE=[3_2, 6_4, 1_6_0, 2_5_6] , __SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , __SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , __SCREAMING_SNAKE_CASE=[1, 2, 5, 8] , __SCREAMING_SNAKE_CASE=[4, 4, 4, 4] , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1e-6 , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=2_5_5 , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , __SCREAMING_SNAKE_CASE , ) snake_case__ : Dict = num_channels snake_case__ : Optional[Any] = num_encoder_blocks snake_case__ : Any = depths snake_case__ : Optional[int] = sr_ratios snake_case__ : Tuple = hidden_sizes snake_case__ : List[str] = patch_sizes snake_case__ : str = strides snake_case__ : Optional[int] = mlp_ratios snake_case__ : Optional[Any] = num_attention_heads snake_case__ : Dict = hidden_act snake_case__ : Optional[int] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : List[Any] = classifier_dropout_prob snake_case__ : int = initializer_range snake_case__ : List[str] = drop_path_rate snake_case__ : int = layer_norm_eps snake_case__ : List[Any] = decoder_hidden_size snake_case__ : List[Any] = kwargs.get("""reshape_last_stage""" , __SCREAMING_SNAKE_CASE ) snake_case__ : Dict = semantic_loss_ignore_index class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = version.parse('''1.11''' ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __UpperCamelCase ( self ): return 1e-4 @property def __UpperCamelCase ( self ): return 1_2
38
1
'''simple docstring''' from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = 42 lowerCamelCase__ = None # Automatically constructed lowerCamelCase__ = "dict" lowerCamelCase__ = None lowerCamelCase__ = field(default='''Translation''' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def __UpperCamelCase ( self ): from .features import Value return {k: Value("""string""" ) for k in sorted(self.languages )} @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = None lowerCamelCase__ = None lowerCamelCase__ = None # Automatically constructed lowerCamelCase__ = "dict" lowerCamelCase__ = None lowerCamelCase__ = field(default='''TranslationVariableLanguages''' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = sorted(set(self.languages ) ) if self.languages else None snake_case__ : int = len(self.languages ) if self.languages else None def __call__( self ): return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = set(self.languages ) if self.languages and set(__SCREAMING_SNAKE_CASE ) - lang_set: raise ValueError( f"Some languages in example ({', '.join(sorted(set(__SCREAMING_SNAKE_CASE ) - lang_set ) )}) are not in valid set ({', '.join(__SCREAMING_SNAKE_CASE )})." ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. snake_case__ : Optional[int] = [] for lang, text in translation_dict.items(): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. snake_case__ , snake_case__ : Any = zip(*sorted(__SCREAMING_SNAKE_CASE ) ) return {"language": languages, "translation": translations} def __UpperCamelCase ( self ): from .features import Sequence, Value return { "language": Sequence(Value("""string""" ) ), "translation": Sequence(Value("""string""" ) ), }
38
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : List[Any]=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : str = None if token is not None: snake_case__ : str = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : List[Any] = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" snake_case__ : str = requests.get(__magic_name__ , headers=__magic_name__ ).json() snake_case__ : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) snake_case__ : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(__magic_name__ ): snake_case__ : Tuple = requests.get(url + f"&page={i + 2}" , headers=__magic_name__ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any]=None ) -> List[str]: '''simple docstring''' snake_case__ : Optional[Any] = None if token is not None: snake_case__ : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : Dict = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" snake_case__ : Union[str, Any] = requests.get(__magic_name__ , headers=__magic_name__ ).json() snake_case__ : Dict = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) snake_case__ : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(__magic_name__ ): snake_case__ : Dict = requests.get(url + f"&page={i + 2}" , headers=__magic_name__ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Dict ) -> Dict: '''simple docstring''' snake_case__ : Optional[Any] = None if token is not None: snake_case__ : Dict = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : str = requests.get(__magic_name__ , headers=__magic_name__ , allow_redirects=__magic_name__ ) snake_case__ : Any = result.headers["""Location"""] snake_case__ : Tuple = requests.get(__magic_name__ , allow_redirects=__magic_name__ ) snake_case__ : int = os.path.join(__magic_name__ , f"{artifact_name}.zip" ) with open(__magic_name__ , """wb""" ) as fp: fp.write(response.content ) def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : str=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Any = [] snake_case__ : Union[str, Any] = [] snake_case__ : Any = None with zipfile.ZipFile(__magic_name__ ) as z: for filename in z.namelist(): if not os.path.isdir(__magic_name__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(__magic_name__ ) as f: for line in f: snake_case__ : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs snake_case__ : str = line[: line.index(""": """ )] snake_case__ : Optional[int] = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed snake_case__ : Dict = line[len("""FAILED """ ) :] failed_tests.append(__magic_name__ ) elif filename == "job_name.txt": snake_case__ : Optional[Any] = line if len(__magic_name__ ) != len(__magic_name__ ): raise ValueError( f"`errors` and `failed_tests` should have the same number of elements. Got {len(__magic_name__ )} for `errors` " f"and {len(__magic_name__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" """ problem.""" ) snake_case__ : Optional[Any] = None if job_name and job_links: snake_case__ : Optional[Any] = job_links.get(__magic_name__ , __magic_name__ ) # A list with elements of the form (line of error, error, failed test) snake_case__ : List[Any] = [x + [y] + [job_link] for x, y in zip(__magic_name__ , __magic_name__ )] return result def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : Union[str, Any]=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : str = [] snake_case__ : Dict = [os.path.join(__magic_name__ , __magic_name__ ) for p in os.listdir(__magic_name__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(__magic_name__ , job_links=__magic_name__ ) ) return errors def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : str=None ) -> List[Any]: '''simple docstring''' snake_case__ : Any = Counter() counter.update([x[1] for x in logs] ) snake_case__ : Dict = counter.most_common() snake_case__ : Any = {} for error, count in counts: if error_filter is None or error not in error_filter: snake_case__ : int = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} snake_case__ : Union[str, Any] = dict(sorted(r.items() , key=lambda __magic_name__ : item[1]["count"] , reverse=__magic_name__ ) ) return r def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> List[Any]: '''simple docstring''' snake_case__ : str = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): snake_case__ : Tuple = test.split("""/""" )[2] else: snake_case__ : Any = None return test def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : Union[str, Any]=None ) -> List[str]: '''simple docstring''' snake_case__ : List[str] = [(x[0], x[1], get_model(x[2] )) for x in logs] snake_case__ : List[Any] = [x for x in logs if x[2] is not None] snake_case__ : Any = {x[2] for x in logs} snake_case__ : Optional[Any] = {} for test in tests: snake_case__ : str = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) snake_case__ : Optional[int] = counter.most_common() snake_case__ : Optional[int] = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} snake_case__ : int = sum(error_counts.values() ) if n_errors > 0: snake_case__ : str = {"""count""": n_errors, """errors""": error_counts} snake_case__ : Union[str, Any] = dict(sorted(r.items() , key=lambda __magic_name__ : item[1]["count"] , reverse=__magic_name__ ) ) return r def UpperCamelCase__ ( __magic_name__ : int ) -> Optional[int]: '''simple docstring''' snake_case__ : Optional[Any] = """| no. | error | status |""" snake_case__ : int = """|-:|:-|:-|""" snake_case__ : int = [header, sep] for error in reduced_by_error: snake_case__ : Union[str, Any] = reduced_by_error[error]["""count"""] snake_case__ : Dict = f"| {count} | {error[:1_00]} | |" lines.append(__magic_name__ ) return "\n".join(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> List[Any]: '''simple docstring''' snake_case__ : List[Any] = """| model | no. of errors | major error | count |""" snake_case__ : Optional[int] = """|-:|-:|-:|-:|""" snake_case__ : Dict = [header, sep] for model in reduced_by_model: snake_case__ : Tuple = reduced_by_model[model]["""count"""] snake_case__ , snake_case__ : Tuple = list(reduced_by_model[model]["""errors"""].items() )[0] snake_case__ : Optional[int] = f"| {model} | {count} | {error[:60]} | {_count} |" lines.append(__magic_name__ ) return "\n".join(__magic_name__ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") A_ : int = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) A_ : Optional[int] = get_job_links(args.workflow_run_id, token=args.token) A_ : Optional[Any] = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: A_ : int = k.find(" / ") A_ : List[Any] = k[index + len(" / ") :] A_ : List[str] = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) A_ : int = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) A_ : str = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error A_ : List[str] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors A_ : Any = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) A_ : Any = reduce_by_error(errors) A_ : Union[str, Any] = reduce_by_model(errors) A_ : Any = make_github_table(reduced_by_error) A_ : Optional[Any] = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
38
1
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : Union[str, Any] ) -> Optional[Any]: # noqa: E741 '''simple docstring''' while r - l > 1: snake_case__ : Optional[Any] = (l + r) // 2 if v[m] >= key: snake_case__ : List[str] = m else: snake_case__ : List[Any] = m # noqa: E741 return r def UpperCamelCase__ ( __magic_name__ : list[int] ) -> int: '''simple docstring''' if len(__magic_name__ ) == 0: return 0 snake_case__ : str = [0] * len(__magic_name__ ) snake_case__ : Any = 1 snake_case__ : Union[str, Any] = v[0] for i in range(1 , len(__magic_name__ ) ): if v[i] < tail[0]: snake_case__ : List[str] = v[i] elif v[i] > tail[length - 1]: snake_case__ : str = v[i] length += 1 else: snake_case__ : List[Any] = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
38
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version A_ : Tuple = get_logger(__name__) class __snake_case : '''simple docstring''' lowerCamelCase__ = '''dummy_data''' lowerCamelCase__ = '''datasets''' lowerCamelCase__ = False def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , ): snake_case__ : List[Any] = 0 snake_case__ : Union[str, Any] = dataset_name snake_case__ : Optional[int] = cache_dir snake_case__ : Union[str, Any] = use_local_dummy_data snake_case__ : int = config # download_callbacks take a single url as input snake_case__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root snake_case__ : Union[str, Any] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general snake_case__ : Union[str, Any] = str(__SCREAMING_SNAKE_CASE ) # to be downloaded snake_case__ : List[str] = None snake_case__ : List[str] = None @property def __UpperCamelCase ( self ): if self._dummy_file is None: snake_case__ : List[str] = self.download_dummy_data() return self._dummy_file @property def __UpperCamelCase ( self ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("""dummy""" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("""dummy""" , self.version_name ) @property def __UpperCamelCase ( self ): return os.path.join(self.dummy_data_folder , """dummy_data.zip""" ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) snake_case__ : Optional[int] = cached_path( __SCREAMING_SNAKE_CASE , cache_dir=self.cache_dir , extract_compressed_file=__SCREAMING_SNAKE_CASE , force_extract=__SCREAMING_SNAKE_CASE ) return os.path.join(__SCREAMING_SNAKE_CASE , self.dummy_file_name ) @property def __UpperCamelCase ( self ): return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __UpperCamelCase ( self ): if self._bucket_url is None: snake_case__ : List[str] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , """/""" ) ) return self._bucket_url @property def __UpperCamelCase ( self ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , """/""" ).split("""/""" )[:-1] ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): if self.load_existing_dummy_data: # dummy data is downloaded and tested snake_case__ : List[Any] = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned snake_case__ : List[Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return self.create_dummy_data_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ): return self.create_dummy_data_list(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return self.create_dummy_data_single(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): return self.download_and_extract(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return self.download_and_extract(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): return path def __UpperCamelCase ( self ): return {} def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for single_url in single_urls: download_callback(__SCREAMING_SNAKE_CASE ) else: snake_case__ : List[str] = single_urls download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = [os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(Path(__SCREAMING_SNAKE_CASE ).name ) ) for x in single_urls] else: snake_case__ : List[Any] = single_urls snake_case__ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(Path(__SCREAMING_SNAKE_CASE ).name ) ) snake_case__ : Optional[int] = value # make sure that values are unique if all(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique snake_case__ : List[Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one snake_case__ : Tuple = all(bool(re.findall("""[0-9]{3,}-of-[0-9]{3,}""" , __SCREAMING_SNAKE_CASE ) ) for url in data_url ) snake_case__ : List[Any] = all( url.startswith("""https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed""" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): snake_case__ : List[str] = [data_url[0]] * len(__SCREAMING_SNAKE_CASE ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case__ : List[Any] = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(single_url.split("""/""" )[-1] ) ) dummy_data_list.append(__SCREAMING_SNAKE_CASE ) return dummy_data_list def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for download_callback in self.download_callbacks: download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case__ : Any = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(data_url.split("""/""" )[-1] ) ) if os.path.exists(__SCREAMING_SNAKE_CASE ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): def _iter_archive_members(__SCREAMING_SNAKE_CASE ): # this preserves the order of the members inside the ZIP archive snake_case__ : List[str] = Path(self.dummy_file ).parent snake_case__ : Dict = path.relative_to(__SCREAMING_SNAKE_CASE ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: snake_case__ : Optional[int] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = Path(__SCREAMING_SNAKE_CASE ) snake_case__ : int = _iter_archive_members(__SCREAMING_SNAKE_CASE ) if self.use_local_dummy_data else path.rglob("""*""" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((""".""", """__""") ): yield file_path.relative_to(__SCREAMING_SNAKE_CASE ).as_posix(), file_path.open("""rb""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[int] = [paths] for path in paths: if os.path.isfile(__SCREAMING_SNAKE_CASE ): if os.path.basename(__SCREAMING_SNAKE_CASE ).startswith((""".""", """__""") ): return yield path else: for dirpath, dirnames, filenames in os.walk(__SCREAMING_SNAKE_CASE ): if os.path.basename(__SCREAMING_SNAKE_CASE ).startswith((""".""", """__""") ): continue dirnames.sort() for filename in sorted(__SCREAMING_SNAKE_CASE ): if filename.startswith((""".""", """__""") ): continue yield os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
38
1
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : str ) -> list[int]: '''simple docstring''' snake_case__ : Dict = [0 for i in range(len(__magic_name__ ) )] # initialize interval's left pointer and right pointer snake_case__ , snake_case__ : List[str] = 0, 0 for i in range(1 , len(__magic_name__ ) ): # case when current index is inside the interval if i <= right_pointer: snake_case__ : List[Any] = min(right_pointer - i + 1 , z_result[i - left_pointer] ) snake_case__ : Tuple = min_edge while go_next(__magic_name__ , __magic_name__ , __magic_name__ ): z_result[i] += 1 # if new index's result gives us more right interval, # we've to update left_pointer and right_pointer if i + z_result[i] - 1 > right_pointer: snake_case__ , snake_case__ : Tuple = i, i + z_result[i] - 1 return z_result def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : list[int] , __magic_name__ : str ) -> bool: '''simple docstring''' return i + z_result[i] < len(__magic_name__ ) and s[z_result[i]] == s[i + z_result[i]] def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : str ) -> int: '''simple docstring''' snake_case__ : Tuple = 0 # concatenate 'pattern' and 'input_str' and call z_function # with concatenated string snake_case__ : Union[str, Any] = z_function(pattern + input_str ) for val in z_result: # if value is greater then length of the pattern string # that means this index is starting position of substring # which is equal to pattern string if val >= len(__magic_name__ ): answer += 1 return answer if __name__ == "__main__": import doctest doctest.testmod()
38
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = IFImgaImgSuperResolutionPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def __UpperCamelCase ( self ): return self._get_superresolution_dummy_components() def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): snake_case__ : List[Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case__ : Tuple = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = floats_tensor((1, 3, 1_6, 1_6) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : int = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __UpperCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __UpperCamelCase ( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __UpperCamelCase ( self ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def __UpperCamelCase ( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __UpperCamelCase ( self ): self._test_save_load_local() def __UpperCamelCase ( self ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
38
1
'''simple docstring''' import os import sys import unittest A_ : Dict = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) A_ : Dict = os.path.join("tests", "models", "bert", "test_modeling_bert.py") A_ : str = os.path.join("tests", "models", "blip", "test_modeling_blip.py") class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Optional[int] = get_test_to_tester_mapping(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = get_test_to_tester_mapping(__SCREAMING_SNAKE_CASE ) snake_case__ : int = {"""BertModelTest""": """BertModelTester"""} snake_case__ : List[str] = { """BlipModelTest""": """BlipModelTester""", """BlipTextImageModelTest""": """BlipTextImageModelsModelTester""", """BlipTextModelTest""": """BlipTextModelTester""", """BlipTextRetrievalModelTest""": """BlipTextRetrievalModelTester""", """BlipVQAModelTest""": """BlipVQAModelTester""", """BlipVisionModelTest""": """BlipVisionModelTester""", } self.assertEqual(get_test_info.to_json(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = get_model_to_test_mapping(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = get_model_to_test_mapping(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = { """BertForMaskedLM""": ["""BertModelTest"""], """BertForMultipleChoice""": ["""BertModelTest"""], """BertForNextSentencePrediction""": ["""BertModelTest"""], """BertForPreTraining""": ["""BertModelTest"""], """BertForQuestionAnswering""": ["""BertModelTest"""], """BertForSequenceClassification""": ["""BertModelTest"""], """BertForTokenClassification""": ["""BertModelTest"""], """BertLMHeadModel""": ["""BertModelTest"""], """BertModel""": ["""BertModelTest"""], } snake_case__ : Any = { """BlipForConditionalGeneration""": ["""BlipTextImageModelTest"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTest"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTest"""], """BlipModel""": ["""BlipModelTest"""], """BlipTextModel""": ["""BlipTextModelTest"""], """BlipVisionModel""": ["""BlipVisionModelTest"""], } self.assertEqual(get_test_info.to_json(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[str] = get_model_to_tester_mapping(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = get_model_to_tester_mapping(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = { """BertForMaskedLM""": ["""BertModelTester"""], """BertForMultipleChoice""": ["""BertModelTester"""], """BertForNextSentencePrediction""": ["""BertModelTester"""], """BertForPreTraining""": ["""BertModelTester"""], """BertForQuestionAnswering""": ["""BertModelTester"""], """BertForSequenceClassification""": ["""BertModelTester"""], """BertForTokenClassification""": ["""BertModelTester"""], """BertLMHeadModel""": ["""BertModelTester"""], """BertModel""": ["""BertModelTester"""], } snake_case__ : Optional[Any] = { """BlipForConditionalGeneration""": ["""BlipTextImageModelsModelTester"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTester"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTester"""], """BlipModel""": ["""BlipModelTester"""], """BlipTextModel""": ["""BlipTextModelTester"""], """BlipVisionModel""": ["""BlipVisionModelTester"""], } self.assertEqual(get_test_info.to_json(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(get_test_info.to_json(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE )
38
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu A_ : Dict = [ "EAGER", "AOT_EAGER", "INDUCTOR", "NVFUSER", "AOT_NVFUSER", "AOT_CUDAGRAPHS", "OFI", "FX2TRT", "ONNXRT", "IPEX", ] def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : List[Any]=None , __magic_name__ : List[str]=None , __magic_name__ : List[str]=None ) -> Dict: '''simple docstring''' snake_case__ : Optional[int] = True while ask_again: snake_case__ : Optional[Any] = input(__magic_name__ ) try: if default is not None and len(__magic_name__ ) == 0: return default return convert_value(__magic_name__ ) if convert_value is not None else result except Exception: if error_message is not None: print(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Any=[] , __magic_name__ : Optional[int]=None , __magic_name__ : int=0 ) -> Optional[int]: '''simple docstring''' snake_case__ : Union[str, Any] = BulletMenu(__magic_name__ , __magic_name__ ) snake_case__ : Optional[Any] = menu.run(default_choice=__magic_name__ ) return convert_value(__magic_name__ ) if convert_value is not None else result def UpperCamelCase__ ( __magic_name__ : Any ) -> int: '''simple docstring''' snake_case__ : Tuple = int(__magic_name__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def UpperCamelCase__ ( __magic_name__ : str ) -> Tuple: '''simple docstring''' snake_case__ : List[Any] = int(__magic_name__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> List[Any]: '''simple docstring''' snake_case__ : Union[str, Any] = int(__magic_name__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def UpperCamelCase__ ( __magic_name__ : List[str] ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Optional[Any] = int(__magic_name__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> List[Any]: '''simple docstring''' snake_case__ : Optional[Any] = int(__magic_name__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> Tuple: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class __snake_case ( argparse.RawDescriptionHelpFormatter ): '''simple docstring''' def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : str = usage.replace("""<command> [<args>] """ , """""" ) return usage
38
1
'''simple docstring''' from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __lt__( self , __SCREAMING_SNAKE_CASE ): return self[-1] < other[-1] def __eq__( self , __SCREAMING_SNAKE_CASE ): return self[-1] == other[-1] def UpperCamelCase__ ( __magic_name__ : list ) -> list: '''simple docstring''' snake_case__ : list[Stack] = [] # sort into stacks for element in collection: snake_case__ : Optional[int] = Stack([element] ) snake_case__ : Optional[Any] = bisect_left(__magic_name__ , __magic_name__ ) if i != len(__magic_name__ ): stacks[i].append(__magic_name__ ) else: stacks.append(__magic_name__ ) # use a heap-based merge to merge stack efficiently snake_case__ : Optional[int] = merge(*(reversed(__magic_name__ ) for stack in stacks) ) return collection if __name__ == "__main__": A_ : Optional[Any] = input("Enter numbers separated by a comma:\n").strip() A_ : Tuple = [int(item) for item in user_input.split(",")] print(patience_sort(unsorted))
38
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( __magic_name__ : list ) -> float: '''simple docstring''' if not nums: raise ValueError("""List is empty""" ) return sum(__magic_name__ ) / len(__magic_name__ ) if __name__ == "__main__": import doctest doctest.testmod()
38
1
'''simple docstring''' import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __get__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError("""unreadable attribute""" ) snake_case__ : List[Any] = """__cached_""" + self.fget.__name__ snake_case__ : str = getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) if cached is None: snake_case__ : Optional[Any] = self.fget(__SCREAMING_SNAKE_CASE ) setattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return cached def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> str: '''simple docstring''' snake_case__ : List[Any] = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f"invalid truth value {val!r}" ) def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> str: '''simple docstring''' if is_torch_fx_proxy(__magic_name__ ): return True if is_torch_available(): import torch if isinstance(__magic_name__ , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(__magic_name__ , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(__magic_name__ , (jnp.ndarray, Tracer) ): return True return isinstance(__magic_name__ , np.ndarray ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> List[str]: '''simple docstring''' return isinstance(__magic_name__ , np.ndarray ) def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> List[Any]: '''simple docstring''' return _is_numpy(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Tuple ) -> List[Any]: '''simple docstring''' import torch return isinstance(__magic_name__ , torch.Tensor ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> Union[str, Any]: '''simple docstring''' return False if not is_torch_available() else _is_torch(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> Union[str, Any]: '''simple docstring''' import torch return isinstance(__magic_name__ , torch.device ) def UpperCamelCase__ ( __magic_name__ : str ) -> Dict: '''simple docstring''' return False if not is_torch_available() else _is_torch_device(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> int: '''simple docstring''' import torch if isinstance(__magic_name__ , __magic_name__ ): if hasattr(__magic_name__ , __magic_name__ ): snake_case__ : Optional[Any] = getattr(__magic_name__ , __magic_name__ ) else: return False return isinstance(__magic_name__ , torch.dtype ) def UpperCamelCase__ ( __magic_name__ : Union[str, Any] ) -> List[str]: '''simple docstring''' return False if not is_torch_available() else _is_torch_dtype(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Union[str, Any] ) -> List[Any]: '''simple docstring''' import tensorflow as tf return isinstance(__magic_name__ , tf.Tensor ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> Union[str, Any]: '''simple docstring''' return False if not is_tf_available() else _is_tensorflow(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(__magic_name__ , """is_symbolic_tensor""" ): return tf.is_symbolic_tensor(__magic_name__ ) return type(__magic_name__ ) == tf.Tensor def UpperCamelCase__ ( __magic_name__ : List[str] ) -> int: '''simple docstring''' return False if not is_tf_available() else _is_tf_symbolic_tensor(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' import jax.numpy as jnp # noqa: F811 return isinstance(__magic_name__ , jnp.ndarray ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> List[str]: '''simple docstring''' return False if not is_flax_available() else _is_jax(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' if isinstance(__magic_name__ , (dict, UserDict) ): return {k: to_py_obj(__magic_name__ ) for k, v in obj.items()} elif isinstance(__magic_name__ , (list, tuple) ): return [to_py_obj(__magic_name__ ) for o in obj] elif is_tf_tensor(__magic_name__ ): return obj.numpy().tolist() elif is_torch_tensor(__magic_name__ ): return obj.detach().cpu().tolist() elif is_jax_tensor(__magic_name__ ): return np.asarray(__magic_name__ ).tolist() elif isinstance(__magic_name__ , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> Union[str, Any]: '''simple docstring''' if isinstance(__magic_name__ , (dict, UserDict) ): return {k: to_numpy(__magic_name__ ) for k, v in obj.items()} elif isinstance(__magic_name__ , (list, tuple) ): return np.array(__magic_name__ ) elif is_tf_tensor(__magic_name__ ): return obj.numpy() elif is_torch_tensor(__magic_name__ ): return obj.detach().cpu().numpy() elif is_jax_tensor(__magic_name__ ): return np.asarray(__magic_name__ ) else: return obj class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : List[Any] = fields(self ) # Safety and consistency checks if not len(__SCREAMING_SNAKE_CASE ): raise ValueError(f"{self.__class__.__name__} has no fields." ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f"{self.__class__.__name__} should not have more than one required field." ) snake_case__ : List[Any] = getattr(self , class_fields[0].name ) snake_case__ : Tuple = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(__SCREAMING_SNAKE_CASE ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = first_field.items() snake_case__ : Dict = True else: try: snake_case__ : Union[str, Any] = iter(__SCREAMING_SNAKE_CASE ) snake_case__ : str = True except TypeError: snake_case__ : int = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(__SCREAMING_SNAKE_CASE ): if ( not isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ) or not len(__SCREAMING_SNAKE_CASE ) == 2 or not isinstance(element[0] , __SCREAMING_SNAKE_CASE ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute snake_case__ : Union[str, Any] = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f"Cannot set key/value for {element}. It needs to be a tuple (key, value)." ) break setattr(self , element[0] , element[1] ) if element[1] is not None: snake_case__ : List[str] = element[1] elif first_field is not None: snake_case__ : int = first_field else: for field in class_fields: snake_case__ : Union[str, Any] = getattr(self , field.name ) if v is not None: snake_case__ : Any = v def __delitem__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance." ) def __UpperCamelCase ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance." ) def __UpperCamelCase ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance." ) def __UpperCamelCase ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance." ) def __getitem__( self , __SCREAMING_SNAKE_CASE ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) super().__setattr__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __setitem__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Will raise a KeyException if needed super().__setitem__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): return tuple(self[k] for k in self.keys() ) class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' @classmethod def __UpperCamelCase ( cls , __SCREAMING_SNAKE_CASE ): raise ValueError( f"{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}" ) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''longest''' lowerCamelCase__ = '''max_length''' lowerCamelCase__ = '''do_not_pad''' class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''pt''' lowerCamelCase__ = '''tf''' lowerCamelCase__ = '''np''' lowerCamelCase__ = '''jax''' class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Union[str, Any] = context_managers snake_case__ : str = ExitStack() def __enter__( self ): for context_manager in self.context_managers: self.stack.enter_context(__SCREAMING_SNAKE_CASE ) def __exit__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.stack.__exit__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Dict = infer_framework(__magic_name__ ) if framework == "tf": snake_case__ : Union[str, Any] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": snake_case__ : int = inspect.signature(model_class.forward ) # PyTorch models else: snake_case__ : Optional[int] = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def UpperCamelCase__ ( __magic_name__ : Any ) -> List[str]: '''simple docstring''' snake_case__ : List[Any] = model_class.__name__ snake_case__ : Union[str, Any] = infer_framework(__magic_name__ ) if framework == "tf": snake_case__ : int = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": snake_case__ : Dict = inspect.signature(model_class.forward ) # PyTorch models else: snake_case__ : List[str] = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def UpperCamelCase__ ( __magic_name__ : MutableMapping , __magic_name__ : str = "" , __magic_name__ : str = "." ) -> Dict: '''simple docstring''' def _flatten_dict(__magic_name__ : str , __magic_name__ : int="" , __magic_name__ : Optional[int]="." ): for k, v in d.items(): snake_case__ : Tuple = str(__magic_name__ ) + delimiter + str(__magic_name__ ) if parent_key else k if v and isinstance(__magic_name__ , __magic_name__ ): yield from flatten_dict(__magic_name__ , __magic_name__ , delimiter=__magic_name__ ).items() else: yield key, v return dict(_flatten_dict(__magic_name__ , __magic_name__ , __magic_name__ ) ) @contextmanager def UpperCamelCase__ ( __magic_name__ : Union[str, Any] , __magic_name__ : bool = False ) -> List[str]: '''simple docstring''' if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def UpperCamelCase__ ( __magic_name__ : Tuple , __magic_name__ : Any=None ) -> Dict: '''simple docstring''' if is_numpy_array(__magic_name__ ): return np.transpose(__magic_name__ , axes=__magic_name__ ) elif is_torch_tensor(__magic_name__ ): return array.T if axes is None else array.permute(*__magic_name__ ) elif is_tf_tensor(__magic_name__ ): import tensorflow as tf return tf.transpose(__magic_name__ , perm=__magic_name__ ) elif is_jax_tensor(__magic_name__ ): return jnp.transpose(__magic_name__ , axes=__magic_name__ ) else: raise ValueError(f"Type not supported for transpose: {type(__magic_name__ )}." ) def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : Optional[Any] ) -> List[Any]: '''simple docstring''' if is_numpy_array(__magic_name__ ): return np.reshape(__magic_name__ , __magic_name__ ) elif is_torch_tensor(__magic_name__ ): return array.reshape(*__magic_name__ ) elif is_tf_tensor(__magic_name__ ): import tensorflow as tf return tf.reshape(__magic_name__ , __magic_name__ ) elif is_jax_tensor(__magic_name__ ): return jnp.reshape(__magic_name__ , __magic_name__ ) else: raise ValueError(f"Type not supported for reshape: {type(__magic_name__ )}." ) def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : Optional[Any]=None ) -> Dict: '''simple docstring''' if is_numpy_array(__magic_name__ ): return np.squeeze(__magic_name__ , axis=__magic_name__ ) elif is_torch_tensor(__magic_name__ ): return array.squeeze() if axis is None else array.squeeze(dim=__magic_name__ ) elif is_tf_tensor(__magic_name__ ): import tensorflow as tf return tf.squeeze(__magic_name__ , axis=__magic_name__ ) elif is_jax_tensor(__magic_name__ ): return jnp.squeeze(__magic_name__ , axis=__magic_name__ ) else: raise ValueError(f"Type not supported for squeeze: {type(__magic_name__ )}." ) def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : int ) -> List[Any]: '''simple docstring''' if is_numpy_array(__magic_name__ ): return np.expand_dims(__magic_name__ , __magic_name__ ) elif is_torch_tensor(__magic_name__ ): return array.unsqueeze(dim=__magic_name__ ) elif is_tf_tensor(__magic_name__ ): import tensorflow as tf return tf.expand_dims(__magic_name__ , axis=__magic_name__ ) elif is_jax_tensor(__magic_name__ ): return jnp.expand_dims(__magic_name__ , axis=__magic_name__ ) else: raise ValueError(f"Type not supported for expand_dims: {type(__magic_name__ )}." ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> Optional[Any]: '''simple docstring''' if is_numpy_array(__magic_name__ ): return np.size(__magic_name__ ) elif is_torch_tensor(__magic_name__ ): return array.numel() elif is_tf_tensor(__magic_name__ ): import tensorflow as tf return tf.size(__magic_name__ ) elif is_jax_tensor(__magic_name__ ): return array.size else: raise ValueError(f"Type not supported for expand_dims: {type(__magic_name__ )}." ) def UpperCamelCase__ ( __magic_name__ : Dict , __magic_name__ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' for key, value in auto_map.items(): if isinstance(__magic_name__ , (tuple, list) ): snake_case__ : Optional[int] = [f"{repo_id}--{v}" if (v is not None and """--""" not in v) else v for v in value] elif value is not None and "--" not in value: snake_case__ : Optional[int] = f"{repo_id}--{value}" return auto_map def UpperCamelCase__ ( __magic_name__ : str ) -> Tuple: '''simple docstring''' for base_class in inspect.getmro(__magic_name__ ): snake_case__ : List[Any] = base_class.__module__ snake_case__ : Tuple = base_class.__name__ if module.startswith("""tensorflow""" ) or module.startswith("""keras""" ) or name == "TFPreTrainedModel": return "tf" elif module.startswith("""torch""" ) or name == "PreTrainedModel": return "pt" elif module.startswith("""flax""" ) or module.startswith("""jax""" ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f"Could not infer framework from class {model_class}." )
38
'''simple docstring''' from __future__ import annotations A_ : str = "Muhammad Umer Farooq" A_ : Optional[Any] = "MIT" A_ : int = "1.0.0" A_ : int = "Muhammad Umer Farooq" A_ : int = "[email protected]" A_ : Dict = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): super().__init__() snake_case__ : list[str] = [] snake_case__ : List[Any] = domain def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: snake_case__ : str = parse.urljoin(self.domain , __SCREAMING_SNAKE_CASE ) self.urls.append(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return ".".join(get_sub_domain_name(__magic_name__ ).split(""".""" )[-2:] ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return parse.urlparse(__magic_name__ ).netloc def UpperCamelCase__ ( __magic_name__ : str = "https://github.com" ) -> list[str]: '''simple docstring''' snake_case__ : List[str] = get_domain_name(__magic_name__ ) # Initialize the parser snake_case__ : Optional[Any] = Parser(__magic_name__ ) try: # Open URL snake_case__ : Any = requests.get(__magic_name__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through snake_case__ : List[str] = set() for link in parser.urls: # open URL. # read = requests.get(link) try: snake_case__ : Tuple = requests.get(__magic_name__ ) # Get the valid email. snake_case__ : List[str] = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(__magic_name__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(__magic_name__ ) if __name__ == "__main__": A_ : str = emails_from_url("https://github.com") print(F'{len(emails)} emails found:') print("\n".join(sorted(emails)))
38
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Dict = logging.get_logger(__name__) A_ : Any = { "camembert-base": "https://huggingface.co/camembert-base/resolve/main/config.json", "umberto-commoncrawl-cased-v1": ( "https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json" ), "umberto-wikipedia-uncased-v1": ( "https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json" ), } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''camembert''' def __init__( self , __SCREAMING_SNAKE_CASE=3_0_5_2_2 , __SCREAMING_SNAKE_CASE=7_6_8 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=3_0_7_2 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE="absolute" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = vocab_size snake_case__ : List[Any] = hidden_size snake_case__ : int = num_hidden_layers snake_case__ : Optional[int] = num_attention_heads snake_case__ : List[str] = hidden_act snake_case__ : str = intermediate_size snake_case__ : str = hidden_dropout_prob snake_case__ : str = attention_probs_dropout_prob snake_case__ : Union[str, Any] = max_position_embeddings snake_case__ : List[Any] = type_vocab_size snake_case__ : int = initializer_range snake_case__ : Any = layer_norm_eps snake_case__ : Union[str, Any] = position_embedding_type snake_case__ : Tuple = use_cache snake_case__ : Dict = classifier_dropout class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def __UpperCamelCase ( self ): if self.task == "multiple-choice": snake_case__ : List[Any] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: snake_case__ : Optional[Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
38
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> Tuple: '''simple docstring''' if not head: return True # split the list to two parts snake_case__ , snake_case__ : Dict = head.next, head while fast and fast.next: snake_case__ : Any = fast.next.next snake_case__ : int = slow.next snake_case__ : Dict = slow.next snake_case__ : List[str] = None # Don't forget here! But forget still works! # reverse the second part snake_case__ : Tuple = None while second: snake_case__ : Tuple = second.next snake_case__ : Any = node snake_case__ : str = second snake_case__ : Optional[Any] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False snake_case__ : List[Any] = node.next snake_case__ : int = head.next return True def UpperCamelCase__ ( __magic_name__ : Any ) -> Optional[Any]: '''simple docstring''' if not head or not head.next: return True # 1. Get the midpoint (slow) snake_case__ : List[Any] = head while fast and fast.next: snake_case__ , snake_case__ : Any = fast.next.next, slow.next # 2. Push the second half into the stack snake_case__ : Tuple = [slow.val] while slow.next: snake_case__ : Optional[Any] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False snake_case__ : str = cur.next return True def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Tuple: '''simple docstring''' if not head or not head.next: return True snake_case__ : int = {} snake_case__ : Union[str, Any] = 0 while head: if head.val in d: d[head.val].append(__magic_name__ ) else: snake_case__ : Tuple = [pos] snake_case__ : Optional[Any] = head.next pos += 1 snake_case__ : int = pos - 1 snake_case__ : str = 0 for v in d.values(): if len(__magic_name__ ) % 2 != 0: middle += 1 else: snake_case__ : List[str] = 0 for i in range(0 , len(__magic_name__ ) ): if v[i] + v[len(__magic_name__ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
38
1
'''simple docstring''' from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer A_ : Optional[int] = logging.get_logger(__name__) A_ : List[str] = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } A_ : List[Any] = { "vocab_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json" }, "merges_file": { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt" }, "tokenizer_config_file": { "facebook/blenderbot_small-90M": ( "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json" ) }, } A_ : Optional[Any] = { "facebook/blenderbot_small-90M": 512, } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = BlenderbotSmallTokenizer def __init__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="<|endoftext|>" , __SCREAMING_SNAKE_CASE="<|endoftext|>" , __SCREAMING_SNAKE_CASE="<|endoftext|>" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): super().__init__( ByteLevelBPETokenizer( vocab=__SCREAMING_SNAKE_CASE , merges=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE , ) , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , unk_token=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) snake_case__ : str = add_prefix_space def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): snake_case__ : int = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): snake_case__ : Union[str, Any] = [self.sep_token_id] snake_case__ : List[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 + sep + token_ids_a + sep ) * [0]
38
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin A_ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ : str = 250004 A_ : str = 250020 @require_sentencepiece @require_tokenizers class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MBartTokenizer lowerCamelCase__ = MBartTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing snake_case__ : Tuple = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self ): snake_case__ : Tuple = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) snake_case__ : int = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) snake_case__ : Optional[int] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) snake_case__ : Optional[int] = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) snake_case__ : Union[str, Any] = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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 __UpperCamelCase ( self ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return snake_case__ : Optional[int] = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = tempfile.mkdtemp() snake_case__ : int = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) snake_case__ : List[str] = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way snake_case__ : Tuple = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True snake_case__ : Any = tempfile.mkdtemp() snake_case__ : Optional[int] = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) snake_case__ : int = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way snake_case__ : List[Any] = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False snake_case__ : Dict = tempfile.mkdtemp() snake_case__ : Union[str, Any] = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way snake_case__ : Dict = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = '''facebook/mbart-large-en-ro''' lowerCamelCase__ = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] lowerCamelCase__ = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] lowerCamelCase__ = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def __UpperCamelCase ( cls ): snake_case__ : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) snake_case__ : Any = 1 return cls def __UpperCamelCase ( self ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 2_5_0_0_2_0 ) def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) snake_case__ : List[str] = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] snake_case__ : List[Any] = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = ["""this is gunna be a long sentence """ * 2_0] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = 1_0 snake_case__ : int = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [2_5_0_0_2_6, 2_5_0_0_0_1] ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = tempfile.mkdtemp() snake_case__ : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = MBartTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) snake_case__ : int = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) snake_case__ : List[str] = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 1_4) , batch.input_ids.shape ) self.assertEqual((2, 1_4) , batch.attention_mask.shape ) snake_case__ : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) snake_case__ : Optional[int] = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=1_0 , return_tensors="""pt""" ) snake_case__ : str = targets["""input_ids"""] snake_case__ : Optional[Any] = shift_tokens_right(__SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[6_2, 3_0_3_4, 2, 2_5_0_0_0_4]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 2_5_0_0_0_1, } , )
38
1
'''simple docstring''' import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer A_ : str = logging.get_logger(__name__) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''AutoTokenizer''' lowerCamelCase__ = ['''tokenizer'''] lowerCamelCase__ = { '''semantic_prompt''': 1, '''coarse_prompt''': 2, '''fine_prompt''': 2, } def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): super().__init__(__SCREAMING_SNAKE_CASE ) snake_case__ : int = speaker_embeddings @classmethod def __UpperCamelCase ( cls , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="speaker_embeddings_path.json" , **__SCREAMING_SNAKE_CASE ): if speaker_embeddings_dict_path is not None: snake_case__ : Dict = get_file_from_repo( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , subfolder=kwargs.pop("""subfolder""" , __SCREAMING_SNAKE_CASE ) , cache_dir=kwargs.pop("""cache_dir""" , __SCREAMING_SNAKE_CASE ) , force_download=kwargs.pop("""force_download""" , __SCREAMING_SNAKE_CASE ) , proxies=kwargs.pop("""proxies""" , __SCREAMING_SNAKE_CASE ) , resume_download=kwargs.pop("""resume_download""" , __SCREAMING_SNAKE_CASE ) , local_files_only=kwargs.pop("""local_files_only""" , __SCREAMING_SNAKE_CASE ) , use_auth_token=kwargs.pop("""use_auth_token""" , __SCREAMING_SNAKE_CASE ) , revision=kwargs.pop("""revision""" , __SCREAMING_SNAKE_CASE ) , ) if speaker_embeddings_path is None: logger.warning( f"`{os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )}` does not exists\n , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json\n dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`." ) snake_case__ : str = None else: with open(__SCREAMING_SNAKE_CASE ) as speaker_embeddings_json: snake_case__ : Optional[int] = json.load(__SCREAMING_SNAKE_CASE ) else: snake_case__ : Tuple = None snake_case__ : List[str] = AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) return cls(tokenizer=__SCREAMING_SNAKE_CASE , speaker_embeddings=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="speaker_embeddings_path.json" , __SCREAMING_SNAKE_CASE="speaker_embeddings" , __SCREAMING_SNAKE_CASE = False , **__SCREAMING_SNAKE_CASE , ): if self.speaker_embeddings is not None: os.makedirs(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , """v2""" ) , exist_ok=__SCREAMING_SNAKE_CASE ) snake_case__ : str = {} snake_case__ : Tuple = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": snake_case__ : Dict = self._load_voice_preset(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict["""repo_or_path"""] , __SCREAMING_SNAKE_CASE , f"{prompt_key}_{key}" ) , voice_preset[key] , allow_pickle=__SCREAMING_SNAKE_CASE , ) snake_case__ : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , f"{prompt_key}_{key}.npy" ) snake_case__ : Any = tmp_dict with open(os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , """w""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) super().save_pretrained(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE ): snake_case__ : Dict = self.speaker_embeddings[voice_preset] snake_case__ : str = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( f"Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}]." ) snake_case__ : Tuple = get_file_from_repo( self.speaker_embeddings.get("""repo_or_path""" , """/""" ) , voice_preset_paths[key] , subfolder=kwargs.pop("""subfolder""" , __SCREAMING_SNAKE_CASE ) , cache_dir=kwargs.pop("""cache_dir""" , __SCREAMING_SNAKE_CASE ) , force_download=kwargs.pop("""force_download""" , __SCREAMING_SNAKE_CASE ) , proxies=kwargs.pop("""proxies""" , __SCREAMING_SNAKE_CASE ) , resume_download=kwargs.pop("""resume_download""" , __SCREAMING_SNAKE_CASE ) , local_files_only=kwargs.pop("""local_files_only""" , __SCREAMING_SNAKE_CASE ) , use_auth_token=kwargs.pop("""use_auth_token""" , __SCREAMING_SNAKE_CASE ) , revision=kwargs.pop("""revision""" , __SCREAMING_SNAKE_CASE ) , ) if path is None: raise ValueError( f"`{os.path.join(self.speaker_embeddings.get('repo_or_path' , '/' ) , voice_preset_paths[key] )}` does not exists\n , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset}\n embeddings." ) snake_case__ : Dict = np.load(__SCREAMING_SNAKE_CASE ) return voice_preset_dict def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE = None ): for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(f"Voice preset unrecognized, missing {key} as a key." ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(f"{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray." ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(f"{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray." ) def __call__( self , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="pt" , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=False , **__SCREAMING_SNAKE_CASE , ): if voice_preset is not None and not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if ( isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): snake_case__ : List[Any] = self._load_voice_preset(__SCREAMING_SNAKE_CASE ) else: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and not voice_preset.endswith(""".npz""" ): snake_case__ : Optional[Any] = voice_preset + """.npz""" snake_case__ : Any = np.load(__SCREAMING_SNAKE_CASE ) if voice_preset is not None: self._validate_voice_preset_dict(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = BatchFeature(data=__SCREAMING_SNAKE_CASE , tensor_type=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = self.tokenizer( __SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , padding="""max_length""" , max_length=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) if voice_preset is not None: snake_case__ : Any = voice_preset return encoded_text
38
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : int = logging.get_logger(__name__) A_ : Dict = { "google/bit-50": "https://huggingface.co/google/bit-50/resolve/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''bit''' lowerCamelCase__ = ['''preactivation''', '''bottleneck'''] lowerCamelCase__ = ['''SAME''', '''VALID'''] def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , __SCREAMING_SNAKE_CASE=[3, 4, 6, 3] , __SCREAMING_SNAKE_CASE="preactivation" , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) if global_padding is not None: if global_padding.upper() in self.supported_padding: snake_case__ : Tuple = global_padding.upper() else: raise ValueError(f"Padding strategy {global_padding} not supported" ) snake_case__ : List[str] = num_channels snake_case__ : Tuple = embedding_size snake_case__ : str = hidden_sizes snake_case__ : Optional[Any] = depths snake_case__ : List[Any] = layer_type snake_case__ : Dict = hidden_act snake_case__ : Union[str, Any] = global_padding snake_case__ : List[str] = num_groups snake_case__ : str = drop_path_rate snake_case__ : List[Any] = embedding_dynamic_padding snake_case__ : List[str] = output_stride snake_case__ : Dict = width_factor snake_case__ : List[str] = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] snake_case__ , snake_case__ : Dict = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
38
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() A_ : List[Any] = logging.get_logger(__name__) def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : Optional[Any]=False , __magic_name__ : Dict=False ) -> Optional[int]: '''simple docstring''' snake_case__ : int = """backbone.""" if is_semantic else """""" snake_case__ : List[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"{prefix}blocks.{i}.norm1.weight", f"beit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"{prefix}blocks.{i}.norm1.bias", f"beit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append( (f"{prefix}blocks.{i}.attn.proj.weight", f"beit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append( (f"{prefix}blocks.{i}.attn.proj.bias", f"beit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"{prefix}blocks.{i}.norm2.weight", f"beit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"{prefix}blocks.{i}.norm2.bias", f"beit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"{prefix}blocks.{i}.mlp.fc1.weight", f"beit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"{prefix}blocks.{i}.mlp.fc1.bias", f"beit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"{prefix}blocks.{i}.mlp.fc2.weight", f"beit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"{prefix}blocks.{i}.mlp.fc2.bias", f"beit.encoder.layer.{i}.output.dense.bias") ) # projection layer + position embeddings rename_keys.extend( [ (f"{prefix}cls_token", """beit.embeddings.cls_token"""), (f"{prefix}patch_embed.proj.weight", """beit.embeddings.patch_embeddings.projection.weight"""), (f"{prefix}patch_embed.proj.bias", """beit.embeddings.patch_embeddings.projection.bias"""), (f"{prefix}pos_embed", """beit.embeddings.position_embeddings"""), ] ) if has_lm_head: # mask token + layernorm rename_keys.extend( [ ("""mask_token""", """beit.embeddings.mask_token"""), ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ] ) else: # layernorm + classification head rename_keys.extend( [ ("""fc_norm.weight""", """beit.pooler.layernorm.weight"""), ("""fc_norm.bias""", """beit.pooler.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : Dict , __magic_name__ : Tuple=False , __magic_name__ : Any=False ) -> Dict: '''simple docstring''' for i in range(config.num_hidden_layers ): snake_case__ : Tuple = """backbone.""" if is_semantic else """""" # queries, keys and values snake_case__ : int = state_dict.pop(f"{prefix}blocks.{i}.attn.qkv.weight" ) snake_case__ : List[str] = state_dict.pop(f"{prefix}blocks.{i}.attn.q_bias" ) snake_case__ : Any = state_dict.pop(f"{prefix}blocks.{i}.attn.v_bias" ) snake_case__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] snake_case__ : Optional[int] = q_bias snake_case__ : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case__ : int = in_proj_weight[ -config.hidden_size :, : ] snake_case__ : List[str] = v_bias # gamma_1 and gamma_2 # we call them lambda because otherwise they are renamed when using .from_pretrained snake_case__ : Tuple = state_dict.pop(f"{prefix}blocks.{i}.gamma_1" ) snake_case__ : str = state_dict.pop(f"{prefix}blocks.{i}.gamma_2" ) snake_case__ : int = gamma_a snake_case__ : Dict = gamma_a def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : List[Any] , __magic_name__ : Any ) -> Optional[int]: '''simple docstring''' snake_case__ : Optional[int] = dct.pop(__magic_name__ ) snake_case__ : str = val def UpperCamelCase__ ( ) -> Dict: '''simple docstring''' snake_case__ : List[Any] = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : Dict = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) return im @torch.no_grad() def UpperCamelCase__ ( __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any=False ) -> Any: '''simple docstring''' snake_case__ : Any = False if """rvlcdip""" in checkpoint_url else True snake_case__ : Optional[Any] = BeitConfig(use_absolute_position_embeddings=__magic_name__ , use_mask_token=__magic_name__ ) # size of the architecture if "large" in checkpoint_url or "dit-l" in checkpoint_url: snake_case__ : Optional[Any] = 10_24 snake_case__ : Optional[Any] = 40_96 snake_case__ : int = 24 snake_case__ : Tuple = 16 # labels if "rvlcdip" in checkpoint_url: snake_case__ : Union[str, Any] = 16 snake_case__ : Dict = """huggingface/label-files""" snake_case__ : str = """rvlcdip-id2label.json""" snake_case__ : Tuple = json.load(open(hf_hub_download(__magic_name__ , __magic_name__ , repo_type="""dataset""" ) , """r""" ) ) snake_case__ : List[str] = {int(__magic_name__ ): v for k, v in idalabel.items()} snake_case__ : int = idalabel snake_case__ : List[str] = {v: k for k, v in idalabel.items()} # load state_dict of original model, remove and rename some keys snake_case__ : List[str] = torch.hub.load_state_dict_from_url(__magic_name__ , map_location="""cpu""" )["""model"""] snake_case__ : Tuple = create_rename_keys(__magic_name__ , has_lm_head=__magic_name__ ) for src, dest in rename_keys: rename_key(__magic_name__ , __magic_name__ , __magic_name__ ) read_in_q_k_v(__magic_name__ , __magic_name__ , has_lm_head=__magic_name__ ) # load HuggingFace model snake_case__ : str = BeitForMaskedImageModeling(__magic_name__ ) if has_lm_head else BeitForImageClassification(__magic_name__ ) model.eval() model.load_state_dict(__magic_name__ ) # Check outputs on an image snake_case__ : Tuple = BeitImageProcessor( size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=__magic_name__ ) snake_case__ : str = prepare_img() snake_case__ : List[Any] = image_processor(images=__magic_name__ , return_tensors="""pt""" ) snake_case__ : Dict = encoding["""pixel_values"""] snake_case__ : Union[str, Any] = model(__magic_name__ ) snake_case__ : Optional[int] = outputs.logits # verify logits snake_case__ : str = [1, 16] if """rvlcdip""" in checkpoint_url else [1, 1_96, 81_92] assert logits.shape == torch.Size(__magic_name__ ), "Shape of logits not as expected" Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) print(f"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__magic_name__ ) if push_to_hub: if has_lm_head: snake_case__ : Optional[int] = """dit-base""" if """base""" in checkpoint_url else """dit-large""" else: snake_case__ : Dict = """dit-base-finetuned-rvlcdip""" if """dit-b""" in checkpoint_url else """dit-large-finetuned-rvlcdip""" image_processor.push_to_hub( repo_path_or_name=Path(__magic_name__ , __magic_name__ ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=__magic_name__ , ) model.push_to_hub( repo_path_or_name=Path(__magic_name__ , __magic_name__ ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=__magic_name__ , ) if __name__ == "__main__": A_ : List[Any] = argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth", type=str, help="URL to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) parser.add_argument( "--push_to_hub", action="store_true", ) A_ : Optional[Any] = parser.parse_args() convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
38
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() A_ : Optional[int] = logging.get_logger(__name__) def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : str=False ) -> Tuple: '''simple docstring''' snake_case__ : int = [] # fmt: off # stem: rename_keys.append(("""cls_token""", """vit.embeddings.cls_token""") ) rename_keys.append(("""pos_embed""", """vit.embeddings.position_embeddings""") ) rename_keys.append(("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias""") ) # backbone rename_keys.append(("""patch_embed.backbone.stem.conv.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.bias""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias""") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias") ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case__ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) # fmt: on return rename_keys def UpperCamelCase__ ( __magic_name__ : Tuple , __magic_name__ : int , __magic_name__ : Tuple=False ) -> str: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: snake_case__ : int = """""" else: snake_case__ : Dict = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case__ : int = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) snake_case__ : Union[str, Any] = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] snake_case__ : Optional[Any] = in_proj_bias[: config.hidden_size] snake_case__ : List[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case__ : List[Any] = in_proj_weight[ -config.hidden_size :, : ] snake_case__ : Optional[int] = in_proj_bias[-config.hidden_size :] def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> List[str]: '''simple docstring''' snake_case__ : str = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(__magic_name__ , __magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : str ) -> Union[str, Any]: '''simple docstring''' snake_case__ : List[str] = dct.pop(__magic_name__ ) snake_case__ : Dict = val def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : Optional[int] = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) return im @torch.no_grad() def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : int=False ) -> Optional[int]: '''simple docstring''' snake_case__ : int = BitConfig( global_padding="""same""" , layer_type="""bottleneck""" , depths=(3, 4, 9) , out_features=["""stage3"""] , embedding_dynamic_padding=__magic_name__ , ) snake_case__ : Optional[int] = ViTHybridConfig(backbone_config=__magic_name__ , image_size=3_84 , num_labels=10_00 ) snake_case__ : Union[str, Any] = False # load original model from timm snake_case__ : List[Any] = timm.create_model(__magic_name__ , pretrained=__magic_name__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case__ : Optional[int] = timm_model.state_dict() if base_model: remove_classification_head_(__magic_name__ ) snake_case__ : int = create_rename_keys(__magic_name__ , __magic_name__ ) for src, dest in rename_keys: rename_key(__magic_name__ , __magic_name__ , __magic_name__ ) read_in_q_k_v(__magic_name__ , __magic_name__ , __magic_name__ ) snake_case__ : str = """huggingface/label-files""" snake_case__ : Union[str, Any] = """imagenet-1k-id2label.json""" snake_case__ : Dict = json.load(open(hf_hub_download(__magic_name__ , __magic_name__ , repo_type="""dataset""" ) , """r""" ) ) snake_case__ : List[Any] = {int(__magic_name__ ): v for k, v in idalabel.items()} snake_case__ : int = idalabel snake_case__ : str = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": snake_case__ : str = ViTHybridModel(__magic_name__ ).eval() else: snake_case__ : Union[str, Any] = ViTHybridForImageClassification(__magic_name__ ).eval() model.load_state_dict(__magic_name__ ) # create image processor snake_case__ : Optional[Any] = create_transform(**resolve_data_config({} , model=__magic_name__ ) ) snake_case__ : Union[str, Any] = transform.transforms snake_case__ : Tuple = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } snake_case__ : Any = ViTHybridImageProcessor( do_resize=__magic_name__ , size={"""shortest_edge""": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=__magic_name__ , crop_size={"""height""": timm_transforms[1].size[0], """width""": timm_transforms[1].size[1]} , do_normalize=__magic_name__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) snake_case__ : Any = prepare_img() snake_case__ : int = transform(__magic_name__ ).unsqueeze(0 ) snake_case__ : List[str] = processor(__magic_name__ , return_tensors="""pt""" ).pixel_values # verify pixel values assert torch.allclose(__magic_name__ , __magic_name__ ) # verify logits with torch.no_grad(): snake_case__ : Optional[Any] = model(__magic_name__ ) snake_case__ : Union[str, Any] = outputs.logits print("""Predicted class:""" , logits.argmax(-1 ).item() ) if base_model: snake_case__ : Dict = timm_model.forward_features(__magic_name__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(__magic_name__ , outputs.pooler_output , atol=1E-3 ) else: snake_case__ : int = timm_model(__magic_name__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__magic_name__ , outputs.logits , atol=1E-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(__magic_name__ ) if push_to_hub: print(f"Pushing model and processor to the hub {vit_name}" ) model.push_to_hub(f"ybelkada/{vit_name}" ) processor.push_to_hub(f"ybelkada/{vit_name}" ) if __name__ == "__main__": A_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) A_ : Union[str, Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
38
1
'''simple docstring''' import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging A_ : Optional[Any] = logging.get_logger(__name__) A_ : str = {"vocab_file": "vocab.json"} A_ : List[str] = { "vocab_file": { "mgp-str": "https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json", } } A_ : Any = {"mgp-str": 27} class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE="[GO]" , __SCREAMING_SNAKE_CASE="[GO]" , __SCREAMING_SNAKE_CASE="[s]" , __SCREAMING_SNAKE_CASE="[GO]" , **__SCREAMING_SNAKE_CASE ): super().__init__( unk_token=__SCREAMING_SNAKE_CASE , bos_token=__SCREAMING_SNAKE_CASE , eos_token=__SCREAMING_SNAKE_CASE , pad_token=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) with open(__SCREAMING_SNAKE_CASE , encoding="""utf-8""" ) as vocab_handle: snake_case__ : List[Any] = json.load(__SCREAMING_SNAKE_CASE ) snake_case__ : int = {v: k for k, v in self.vocab.items()} @property def __UpperCamelCase ( self ): return len(self.vocab ) def __UpperCamelCase ( self ): return dict(self.vocab , **self.added_tokens_encoder ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = [] for s in text: char_tokens.extend(__SCREAMING_SNAKE_CASE ) return char_tokens def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): return self.vocab.get(__SCREAMING_SNAKE_CASE , self.vocab.get(self.unk_token ) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): return self.decoder.get(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): if not os.path.isdir(__SCREAMING_SNAKE_CASE ): logger.error("""Vocabulary path ({}) should be a directory""".format(__SCREAMING_SNAKE_CASE ) ) return snake_case__ : int = os.path.join( __SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) with open(__SCREAMING_SNAKE_CASE , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=__SCREAMING_SNAKE_CASE , ensure_ascii=__SCREAMING_SNAKE_CASE ) + """\n""" ) return (vocab_file,)
38
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = 42 class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("DownEncoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE=True , ): super().__init__() snake_case__ : str = layers_per_block snake_case__ : int = torch.nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : List[Any] = None snake_case__ : List[Any] = nn.ModuleList([] ) # down snake_case__ : Union[str, Any] = block_out_channels[0] for i, down_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = output_channel snake_case__ : Union[str, Any] = block_out_channels[i] snake_case__ : int = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : str = get_down_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) self.down_blocks.append(__SCREAMING_SNAKE_CASE ) # mid snake_case__ : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # out snake_case__ : Tuple = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : str = 2 * out_channels if double_z else out_channels snake_case__ : int = nn.Convad(block_out_channels[-1] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : Union[str, Any] = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = x snake_case__ : int = self.conv_in(__SCREAMING_SNAKE_CASE ) if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) # middle snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: for down_block in self.down_blocks: snake_case__ : Dict = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE ) else: # down for down_block in self.down_blocks: snake_case__ : List[str] = down_block(__SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = self.mid_block(__SCREAMING_SNAKE_CASE ) # post-process snake_case__ : Any = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : str = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("UpDecoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE="group" , ): super().__init__() snake_case__ : Any = layers_per_block snake_case__ : Optional[Any] = nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : Union[str, Any] = None snake_case__ : Dict = nn.ModuleList([] ) snake_case__ : Optional[int] = in_channels if norm_type == """spatial""" else None # mid snake_case__ : Tuple = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # up snake_case__ : List[Any] = list(reversed(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[Any] = reversed_block_out_channels[0] for i, up_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = output_channel snake_case__ : Optional[Any] = reversed_block_out_channels[i] snake_case__ : List[str] = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : int = get_up_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block + 1 , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , prev_output_channel=__SCREAMING_SNAKE_CASE , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , resnet_time_scale_shift=__SCREAMING_SNAKE_CASE , ) self.up_blocks.append(__SCREAMING_SNAKE_CASE ) snake_case__ : int = output_channel # out if norm_type == "spatial": snake_case__ : List[Any] = SpatialNorm(block_out_channels[0] , __SCREAMING_SNAKE_CASE ) else: snake_case__ : Any = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : Union[str, Any] = nn.Convad(block_out_channels[0] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : int = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): snake_case__ : Union[str, Any] = z snake_case__ : Any = self.conv_in(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle snake_case__ : int = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) snake_case__ : int = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : List[str] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : Dict = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : List[Any] = self.mid_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : Dict = up_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # post-process if latent_embeds is None: snake_case__ : Optional[Any] = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) else: snake_case__ : str = self.conv_norm_out(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="random" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True ): super().__init__() snake_case__ : int = n_e snake_case__ : Optional[int] = vq_embed_dim snake_case__ : int = beta snake_case__ : Optional[int] = legacy snake_case__ : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) snake_case__ : List[str] = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) snake_case__ : Optional[Any] = self.used.shape[0] snake_case__ : List[str] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": snake_case__ : Dict = self.re_embed snake_case__ : List[str] = self.re_embed + 1 print( f"Remapping {self.n_e} indices to {self.re_embed} indices. " f"Using {self.unknown_index} for unknown indices." ) else: snake_case__ : Union[str, Any] = n_e snake_case__ : str = sane_index_shape def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : Dict = inds.reshape(ishape[0] , -1 ) snake_case__ : Any = self.used.to(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = (inds[:, :, None] == used[None, None, ...]).long() snake_case__ : List[Any] = match.argmax(-1 ) snake_case__ : List[str] = match.sum(2 ) < 1 if self.unknown_index == "random": snake_case__ : List[str] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: snake_case__ : Optional[Any] = self.unknown_index return new.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : int = inds.reshape(ishape[0] , -1 ) snake_case__ : Optional[int] = self.used.to(__SCREAMING_SNAKE_CASE ) if self.re_embed > self.used.shape[0]: # extra token snake_case__ : List[Any] = 0 # simply set to zero snake_case__ : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __SCREAMING_SNAKE_CASE ) return back.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): # reshape z -> (batch, height, width, channel) and flatten snake_case__ : Any = z.permute(0 , 2 , 3 , 1 ).contiguous() snake_case__ : Optional[Any] = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z snake_case__ : Dict = torch.argmin(torch.cdist(__SCREAMING_SNAKE_CASE , self.embedding.weight ) , dim=1 ) snake_case__ : Union[str, Any] = self.embedding(__SCREAMING_SNAKE_CASE ).view(z.shape ) snake_case__ : List[str] = None snake_case__ : Union[str, Any] = None # compute loss for embedding if not self.legacy: snake_case__ : Tuple = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: snake_case__ : List[Any] = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients snake_case__ : Any = z + (z_q - z).detach() # reshape back to match original input shape snake_case__ : Union[str, Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: snake_case__ : List[Any] = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis snake_case__ : str = self.remap_to_used(__SCREAMING_SNAKE_CASE ) snake_case__ : str = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: snake_case__ : Tuple = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # shape specifying (batch, height, width, channel) if self.remap is not None: snake_case__ : List[Any] = indices.reshape(shape[0] , -1 ) # add batch axis snake_case__ : Optional[int] = self.unmap_to_all(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = indices.reshape(-1 ) # flatten again # get quantized latent vectors snake_case__ : int = self.embedding(__SCREAMING_SNAKE_CASE ) if shape is not None: snake_case__ : str = z_q.view(__SCREAMING_SNAKE_CASE ) # reshape back to match original input shape snake_case__ : str = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): snake_case__ : Tuple = parameters snake_case__ , snake_case__ : Any = torch.chunk(__SCREAMING_SNAKE_CASE , 2 , dim=1 ) snake_case__ : Union[str, Any] = torch.clamp(self.logvar , -30.0 , 20.0 ) snake_case__ : Optional[int] = deterministic snake_case__ : Optional[int] = torch.exp(0.5 * self.logvar ) snake_case__ : Any = torch.exp(self.logvar ) if self.deterministic: snake_case__ : List[str] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE = None ): # make sure sample is on the same device as the parameters and has same dtype snake_case__ : Dict = randn_tensor( self.mean.shape , generator=__SCREAMING_SNAKE_CASE , device=self.parameters.device , dtype=self.parameters.dtype ) snake_case__ : Optional[int] = self.mean + self.std * sample return x def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) snake_case__ : Any = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): return self.mean
38
1
'''simple docstring''' from __future__ import annotations A_ : str = "Muhammad Umer Farooq" A_ : Optional[Any] = "MIT" A_ : int = "1.0.0" A_ : int = "Muhammad Umer Farooq" A_ : int = "[email protected]" A_ : Dict = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): super().__init__() snake_case__ : list[str] = [] snake_case__ : List[Any] = domain def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: snake_case__ : str = parse.urljoin(self.domain , __SCREAMING_SNAKE_CASE ) self.urls.append(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return ".".join(get_sub_domain_name(__magic_name__ ).split(""".""" )[-2:] ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return parse.urlparse(__magic_name__ ).netloc def UpperCamelCase__ ( __magic_name__ : str = "https://github.com" ) -> list[str]: '''simple docstring''' snake_case__ : List[str] = get_domain_name(__magic_name__ ) # Initialize the parser snake_case__ : Optional[Any] = Parser(__magic_name__ ) try: # Open URL snake_case__ : Any = requests.get(__magic_name__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through snake_case__ : List[str] = set() for link in parser.urls: # open URL. # read = requests.get(link) try: snake_case__ : Tuple = requests.get(__magic_name__ ) # Get the valid email. snake_case__ : List[str] = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(__magic_name__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(__magic_name__ ) if __name__ == "__main__": A_ : str = emails_from_url("https://github.com") print(F'{len(emails)} emails found:') print("\n".join(sorted(emails)))
38
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1_6 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=[0, 1, 2, 3] , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_7 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=[1, 3_8_4, 2_4, 2_4] , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , ): snake_case__ : str = parent snake_case__ : Union[str, Any] = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : Optional[int] = patch_size snake_case__ : List[str] = num_channels snake_case__ : Any = is_training snake_case__ : int = use_labels snake_case__ : str = hidden_size snake_case__ : Tuple = num_hidden_layers snake_case__ : str = backbone_out_indices snake_case__ : List[Any] = num_attention_heads snake_case__ : Dict = intermediate_size snake_case__ : Optional[Any] = hidden_act snake_case__ : str = hidden_dropout_prob snake_case__ : int = attention_probs_dropout_prob snake_case__ : Dict = initializer_range snake_case__ : Optional[int] = num_labels snake_case__ : str = backbone_featmap_shape snake_case__ : List[Any] = scope snake_case__ : Optional[Any] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) snake_case__ : List[Any] = (image_size // patch_size) ** 2 snake_case__ : Union[str, Any] = num_patches + 1 def __UpperCamelCase ( self ): snake_case__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : str = None if self.use_labels: snake_case__ : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): snake_case__ : Any = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [9_6, 1_9_2, 3_8_4, 7_6_8], """num_groups""": 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , 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=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=__SCREAMING_SNAKE_CASE , backbone_featmap_shape=self.backbone_featmap_shape , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = DPTModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Union[str, Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = self.num_labels snake_case__ : str = DPTForDepthEstimation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Optional[Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = self.num_labels snake_case__ : Dict = DPTForSemanticSegmentation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : str = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () lowerCamelCase__ = ( { '''depth-estimation''': DPTForDepthEstimation, '''feature-extraction''': DPTModel, '''image-segmentation''': DPTForSemanticSegmentation, } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : List[Any] = DPTModelTester(self ) snake_case__ : Any = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""DPT does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Tuple = model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : str = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : List[str] = [*signature.parameters.keys()] snake_case__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : int = True if model_class in get_values(__SCREAMING_SNAKE_CASE ): continue snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.train() snake_case__ : Optional[Any] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCamelCase ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Union[str, Any] = False snake_case__ : str = True if model_class in get_values(__SCREAMING_SNAKE_CASE ) or not model_class.supports_gradient_checkpointing: continue snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.train() snake_case__ : List[str] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCamelCase ( self ): snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : str = _config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: snake_case__ : Any = model_class(config=__SCREAMING_SNAKE_CASE ) # Skip the check for the backbone snake_case__ : str = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": snake_case__ : Optional[int] = [f"{name}.{key}" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCamelCase ( self ): pass @slow def __UpperCamelCase ( self ): for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: snake_case__ : List[str] = DPTModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Dict = """add""" with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = DPTForDepthEstimation(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( ) -> Dict: '''simple docstring''' snake_case__ : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision @slow class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Dict = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" ) snake_case__ : Union[str, Any] = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = prepare_img() snake_case__ : Optional[int] = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): snake_case__ : Dict = model(**__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = outputs.predicted_depth # verify the predicted depth snake_case__ : Any = torch.Size((1, 3_8_4, 3_8_4) ) self.assertEqual(predicted_depth.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0 , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
1
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def UpperCamelCase__ ( __magic_name__ : str = "laptop" ) -> DataFrame: '''simple docstring''' snake_case__ : Union[str, Any] = f"https://www.amazon.in/laptop/s?k={product}" snake_case__ : List[str] = { """User-Agent""": """Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36""", """Accept-Language""": """en-US, en;q=0.5""", } snake_case__ : int = BeautifulSoup(requests.get(__magic_name__ , headers=__magic_name__ ).text ) # Initialize a Pandas dataframe with the column titles snake_case__ : Optional[Any] = DataFrame( columns=[ """Product Title""", """Product Link""", """Current Price of the product""", """Product Rating""", """MRP of the product""", """Discount""", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( """div""" , attrs={"""class""": """s-result-item""", """data-component-type""": """s-search-result"""} , ) , soup.find_all("""div""" , attrs={"""class""": """a-row a-size-base a-color-base"""} ) , ): try: snake_case__ : Optional[int] = item.ha.text snake_case__ : Any = """https://www.amazon.in/""" + item.ha.a["""href"""] snake_case__ : List[str] = item.find("""span""" , attrs={"""class""": """a-offscreen"""} ).text try: snake_case__ : Dict = item.find("""span""" , attrs={"""class""": """a-icon-alt"""} ).text except AttributeError: snake_case__ : Optional[int] = """Not available""" try: snake_case__ : Tuple = ( """₹""" + item.find( """span""" , attrs={"""class""": """a-price a-text-price"""} ).text.split("""₹""" )[1] ) except AttributeError: snake_case__ : Optional[Any] = """""" try: snake_case__ : str = float( ( ( float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) - float(product_price.strip("""₹""" ).replace(""",""" , """""" ) ) ) / float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) ) * 1_00 ) except ValueError: snake_case__ : List[Any] = float("""nan""" ) except AttributeError: pass snake_case__ : str = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] snake_case__ : List[Any] = """ """ snake_case__ : Union[str, Any] = """ """ data_frame.index += 1 return data_frame if __name__ == "__main__": A_ : int = "headphones" get_amazon_product_data(product).to_csv(F'Amazon Product Data for {product}.csv')
38
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Dict: '''simple docstring''' snake_case__ : int = botoa.client("""iam""" ) snake_case__ : Union[str, Any] = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=__magic_name__ , AssumeRolePolicyDocument=json.dumps(__magic_name__ , indent=2 ) ) snake_case__ : Dict = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=__magic_name__ , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(__magic_name__ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def UpperCamelCase__ ( __magic_name__ : Any ) -> Tuple: '''simple docstring''' snake_case__ : List[str] = botoa.client("""iam""" ) return iam_client.get_role(RoleName=__magic_name__ )["Role"]["Arn"] def UpperCamelCase__ ( ) -> Tuple: '''simple docstring''' snake_case__ : Union[str, Any] = _ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , __magic_name__ , ) snake_case__ : List[Any] = None if credentials_configuration == 0: snake_case__ : Dict = _ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) snake_case__ : List[str] = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) snake_case__ : List[str] = _ask_field("""AWS Access Key ID: """ ) snake_case__ : int = aws_access_key_id snake_case__ : Optional[Any] = _ask_field("""AWS Secret Access Key: """ ) snake_case__ : List[str] = aws_secret_access_key snake_case__ : Tuple = _ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) snake_case__ : Optional[int] = aws_region snake_case__ : int = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , __magic_name__ , ) if role_management == 0: snake_case__ : Optional[Any] = _ask_field("""Enter your IAM role name: """ ) else: snake_case__ : Optional[int] = """accelerate_sagemaker_execution_role""" print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(__magic_name__ ) snake_case__ : Dict = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Any = None if is_custom_docker_image: snake_case__ : str = _ask_field("""Enter your Docker image: """ , lambda __magic_name__ : str(__magic_name__ ).lower() ) snake_case__ : Tuple = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : List[Any] = None if is_sagemaker_inputs_enabled: snake_case__ : str = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Optional[int] = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Optional[Any] = None if is_sagemaker_metrics_enabled: snake_case__ : List[Any] = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Tuple = _ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) snake_case__ : Any = {} snake_case__ : List[Any] = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_dynamo: snake_case__ : str = """dynamo_""" snake_case__ : Tuple = _ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) snake_case__ : List[str] = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_custom_options: snake_case__ : str = _ask_options( """Which mode do you want to use?""" , __magic_name__ , lambda __magic_name__ : TORCH_DYNAMO_MODES[int(__magic_name__ )] , default="""default""" , ) snake_case__ : Union[str, Any] = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : str = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Dict = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: snake_case__ : List[str] = _ask_options( __magic_name__ , __magic_name__ , lambda __magic_name__ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(__magic_name__ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" snake_case__ : Optional[int] = _ask_field(__magic_name__ , lambda __magic_name__ : str(__magic_name__ ).lower() , default="""ml.p3.2xlarge""" ) snake_case__ : Dict = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): snake_case__ : Optional[Any] = _ask_field( """How many machines do you want use? [1]: """ , __magic_name__ , default=1 , ) snake_case__ : Union[str, Any] = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=__magic_name__ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=__magic_name__ , use_cpu=__magic_name__ , dynamo_config=__magic_name__ , eca_instance_type=__magic_name__ , profile=__magic_name__ , region=__magic_name__ , iam_role_name=__magic_name__ , mixed_precision=__magic_name__ , num_machines=__magic_name__ , sagemaker_inputs_file=__magic_name__ , sagemaker_metrics_file=__magic_name__ , )
38
1
'''simple docstring''' import argparse import os import re A_ : Optional[int] = "src/diffusers" # Pattern that looks at the indentation in a line. A_ : Optional[int] = re.compile(R"^(\s*)\S") # Pattern that matches `"key":" and puts `key` in group 0. A_ : str = re.compile(R"^\s*\"([^\"]+)\":") # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. A_ : Optional[int] = re.compile(R"^\s*_import_structure\[\"([^\"]+)\"\]") # Pattern that matches `"key",` and puts `key` in group 0. A_ : str = re.compile(R"^\s*\"([^\"]+)\",\s*$") # Pattern that matches any `[stuff]` and puts `stuff` in group 0. A_ : List[Any] = re.compile(R"\[([^\]]+)\]") def UpperCamelCase__ ( __magic_name__ : str ) -> List[str]: '''simple docstring''' snake_case__ : Dict = _re_indent.search(__magic_name__ ) return "" if search is None else search.groups()[0] def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : List[Any]="" , __magic_name__ : Optional[Any]=None , __magic_name__ : List[str]=None ) -> List[str]: '''simple docstring''' snake_case__ : List[str] = 0 snake_case__ : List[Any] = code.split("""\n""" ) if start_prompt is not None: while not lines[index].startswith(__magic_name__ ): index += 1 snake_case__ : Dict = ["""\n""".join(lines[:index] )] else: snake_case__ : Tuple = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). snake_case__ : Tuple = [lines[index]] index += 1 while index < len(__magic_name__ ) and (end_prompt is None or not lines[index].startswith(__magic_name__ )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(__magic_name__ ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + """ """ ): current_block.append(lines[index] ) blocks.append("""\n""".join(__magic_name__ ) ) if index < len(__magic_name__ ) - 1: snake_case__ : List[str] = [lines[index + 1]] index += 1 else: snake_case__ : Union[str, Any] = [] else: blocks.append("""\n""".join(__magic_name__ ) ) snake_case__ : List[Any] = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(__magic_name__ ) > 0: blocks.append("""\n""".join(__magic_name__ ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(__magic_name__ ): blocks.append("""\n""".join(lines[index:] ) ) return blocks def UpperCamelCase__ ( __magic_name__ : int ) -> int: '''simple docstring''' def _inner(__magic_name__ : List[Any] ): return key(__magic_name__ ).lower().replace("""_""" , """""" ) return _inner def UpperCamelCase__ ( __magic_name__ : Dict , __magic_name__ : Optional[int]=None ) -> Optional[Any]: '''simple docstring''' def noop(__magic_name__ : Union[str, Any] ): return x if key is None: snake_case__ : Optional[int] = noop # Constants are all uppercase, they go first. snake_case__ : Tuple = [obj for obj in objects if key(__magic_name__ ).isupper()] # Classes are not all uppercase but start with a capital, they go second. snake_case__ : Any = [obj for obj in objects if key(__magic_name__ )[0].isupper() and not key(__magic_name__ ).isupper()] # Functions begin with a lowercase, they go last. snake_case__ : str = [obj for obj in objects if not key(__magic_name__ )[0].isupper()] snake_case__ : Dict = ignore_underscore(__magic_name__ ) return sorted(__magic_name__ , key=__magic_name__ ) + sorted(__magic_name__ , key=__magic_name__ ) + sorted(__magic_name__ , key=__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' def _replace(__magic_name__ : Tuple ): snake_case__ : Union[str, Any] = match.groups()[0] if "," not in imports: return f"[{imports}]" snake_case__ : Any = [part.strip().replace("""\"""" , """""" ) for part in imports.split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: snake_case__ : Optional[int] = keys[:-1] return "[" + ", ".join([f"\"{k}\"" for k in sort_objects(__magic_name__ )] ) + "]" snake_case__ : Any = import_statement.split("""\n""" ) if len(__magic_name__ ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. snake_case__ : List[str] = 2 if lines[1].strip() == """[""" else 1 snake_case__ : Union[str, Any] = [(i, _re_strip_line.search(__magic_name__ ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] snake_case__ : List[Any] = sort_objects(__magic_name__ , key=lambda __magic_name__ : x[1] ) snake_case__ : Any = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(__magic_name__ ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: snake_case__ : Dict = _re_bracket_content.sub(_replace , lines[1] ) else: snake_case__ : int = [part.strip().replace("""\"""" , """""" ) for part in lines[1].split(""",""" )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: snake_case__ : Any = keys[:-1] snake_case__ : Tuple = get_indent(lines[1] ) + """, """.join([f"\"{k}\"" for k in sort_objects(__magic_name__ )] ) return "\n".join(__magic_name__ ) else: # Finally we have to deal with imports fitting on one line snake_case__ : List[Any] = _re_bracket_content.sub(_replace , __magic_name__ ) return import_statement def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Optional[int]=True ) -> Optional[int]: '''simple docstring''' with open(__magic_name__ , """r""" ) as f: snake_case__ : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 snake_case__ : Any = split_code_in_indented_blocks( __magic_name__ , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(__magic_name__ ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. snake_case__ : int = main_blocks[block_idx] snake_case__ : Optional[Any] = block.split("""\n""" ) # Get to the start of the imports. snake_case__ : Union[str, Any] = 0 while line_idx < len(__magic_name__ ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: snake_case__ : Dict = len(__magic_name__ ) else: line_idx += 1 if line_idx >= len(__magic_name__ ): continue # Ignore beginning and last line: they don't contain anything. snake_case__ : Any = """\n""".join(block_lines[line_idx:-1] ) snake_case__ : Optional[int] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. snake_case__ : int = split_code_in_indented_blocks(__magic_name__ , indent_level=__magic_name__ ) # We have two categories of import key: list or _import_structure[key].append/extend snake_case__ : Any = _re_direct_key if """_import_structure""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. snake_case__ : Any = [(pattern.search(__magic_name__ ).groups()[0] if pattern.search(__magic_name__ ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. snake_case__ : Optional[int] = [(i, key) for i, key in enumerate(__magic_name__ ) if key is not None] snake_case__ : Any = [x[0] for x in sorted(__magic_name__ , key=lambda __magic_name__ : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. snake_case__ : Dict = 0 snake_case__ : List[str] = [] for i in range(len(__magic_name__ ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: snake_case__ : Union[str, Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(__magic_name__ ) count += 1 # And we put our main block back together with its first and last line. snake_case__ : List[Any] = """\n""".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(__magic_name__ ): if check_only: return True else: print(f"Overwriting {file}." ) with open(__magic_name__ , """w""" ) as f: f.write("""\n""".join(__magic_name__ ) ) def UpperCamelCase__ ( __magic_name__ : int=True ) -> Optional[Any]: '''simple docstring''' snake_case__ : Dict = [] for root, _, files in os.walk(__magic_name__ ): if "__init__.py" in files: snake_case__ : List[Any] = sort_imports(os.path.join(__magic_name__ , """__init__.py""" ) , check_only=__magic_name__ ) if result: snake_case__ : Optional[Any] = [os.path.join(__magic_name__ , """__init__.py""" )] if len(__magic_name__ ) > 0: raise ValueError(f"Would overwrite {len(__magic_name__ )} files, run `make style`." ) if __name__ == "__main__": A_ : Tuple = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") A_ : Union[str, Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
38
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def UpperCamelCase__ ( __magic_name__ : str = "laptop" ) -> DataFrame: '''simple docstring''' snake_case__ : Union[str, Any] = f"https://www.amazon.in/laptop/s?k={product}" snake_case__ : List[str] = { """User-Agent""": """Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36""", """Accept-Language""": """en-US, en;q=0.5""", } snake_case__ : int = BeautifulSoup(requests.get(__magic_name__ , headers=__magic_name__ ).text ) # Initialize a Pandas dataframe with the column titles snake_case__ : Optional[Any] = DataFrame( columns=[ """Product Title""", """Product Link""", """Current Price of the product""", """Product Rating""", """MRP of the product""", """Discount""", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( """div""" , attrs={"""class""": """s-result-item""", """data-component-type""": """s-search-result"""} , ) , soup.find_all("""div""" , attrs={"""class""": """a-row a-size-base a-color-base"""} ) , ): try: snake_case__ : Optional[int] = item.ha.text snake_case__ : Any = """https://www.amazon.in/""" + item.ha.a["""href"""] snake_case__ : List[str] = item.find("""span""" , attrs={"""class""": """a-offscreen"""} ).text try: snake_case__ : Dict = item.find("""span""" , attrs={"""class""": """a-icon-alt"""} ).text except AttributeError: snake_case__ : Optional[int] = """Not available""" try: snake_case__ : Tuple = ( """₹""" + item.find( """span""" , attrs={"""class""": """a-price a-text-price"""} ).text.split("""₹""" )[1] ) except AttributeError: snake_case__ : Optional[Any] = """""" try: snake_case__ : str = float( ( ( float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) - float(product_price.strip("""₹""" ).replace(""",""" , """""" ) ) ) / float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) ) * 1_00 ) except ValueError: snake_case__ : List[Any] = float("""nan""" ) except AttributeError: pass snake_case__ : str = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] snake_case__ : List[Any] = """ """ snake_case__ : Union[str, Any] = """ """ data_frame.index += 1 return data_frame if __name__ == "__main__": A_ : int = "headphones" get_amazon_product_data(product).to_csv(F'Amazon Product Data for {product}.csv')
38
1
'''simple docstring''' import math_equivalence # From: git+https://github.com/hendrycks/math.git import datasets A_ : Optional[int] = "\\n@article{hendrycksmath2021,\n title={Measuring Mathematical Problem Solving With the MATH Dataset},\n author={Dan Hendrycks\n and Collin Burns\n and Saurav Kadavath\n and Akul Arora\n and Steven Basart\n and Eric Tang\n and Dawn Song\n and Jacob Steinhardt},\n journal={arXiv preprint arXiv:2103.03874},\n year={2021}\n}\n" A_ : List[Any] = "\\nThis metric is used to assess performance on the Mathematics Aptitude Test of Heuristics (MATH) dataset.\nIt first canonicalizes the inputs (e.g., converting \"1/2\" to \"\\frac{1}{2}\") and then computes accuracy.\n" A_ : Optional[int] = R"\nCalculates accuracy after canonicalizing inputs.\n\nArgs:\n predictions: list of predictions to score. Each prediction\n is a string that contains natural language and LaTex.\n references: list of reference for each prediction. Each\n reference is a string that contains natural language\n and LaTex.\nReturns:\n accuracy: accuracy after canonicalizing inputs\n (e.g., converting \"1/2\" to \"\\frac{1}{2}\")\n\nExamples:\n >>> metric = datasets.load_metric(\"competition_math\")\n >>> results = metric.compute(references=[\"\\frac{1}{2}\"], predictions=[\"1/2\"])\n >>> print(results)\n {'accuracy': 1.0}\n" @datasets.utils.file_utils.add_end_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __snake_case ( datasets.Metric ): '''simple docstring''' def __UpperCamelCase ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" ), """references""": datasets.Value("""string""" ), } ) , homepage="""https://github.com/hendrycks/math""" , codebase_urls=["""https://github.com/hendrycks/math"""] , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = 0.0 for i, j in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): n_correct += 1.0 if math_equivalence.is_equiv(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else 0.0 snake_case__ : Optional[Any] = n_correct / len(__SCREAMING_SNAKE_CASE ) return { "accuracy": accuracy, }
38
'''simple docstring''' import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = LongformerTokenizer lowerCamelCase__ = True lowerCamelCase__ = LongformerTokenizerFast lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case__ : Union[str, Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] snake_case__ : Optional[int] = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) snake_case__ : int = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] snake_case__ : Any = {"""unk_token""": """<unk>"""} snake_case__ : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) snake_case__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : str = """lower newer""" snake_case__ : Dict = """lower newer""" return input_text, output_text def __UpperCamelCase ( self ): snake_case__ : int = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case__ : Tuple = """lower newer""" snake_case__ : Optional[Any] = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] snake_case__ : Tuple = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) # , add_prefix_space=True) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokens + [tokenizer.unk_token] snake_case__ : List[Any] = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Tuple = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [0, 3_1_4_1_4, 2_3_2, 3_2_8, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [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] , ) @slow def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.tokenizer_class.from_pretrained("""allenai/longformer-base-4096""" ) snake_case__ : int = tokenizer.encode("""sequence builders""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer.encode( """sequence builders""" , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.get_tokenizer() snake_case__ : int = """Encode this sequence.""" snake_case__ : Union[str, Any] = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments snake_case__ : Optional[int] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) snake_case__ : List[str] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Testing spaces after special tokens snake_case__ : List[str] = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE )} ) # mask token has a left space snake_case__ : Dict = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) snake_case__ : str = """Encode <mask> sequence""" snake_case__ : Tuple = """Encode <mask>sequence""" snake_case__ : Union[str, Any] = tokenizer.encode(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = encoded.index(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer.encode(__SCREAMING_SNAKE_CASE ) snake_case__ : str = encoded.index(__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = """A, <mask> AllenNLP sentence.""" snake_case__ : str = tokenizer_r.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer_p.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) snake_case__ : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) snake_case__ : Dict = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def __UpperCamelCase ( self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): snake_case__ : Any = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) snake_case__ : List[str] = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state["""add_prefix_space"""] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state["""trim_offsets"""] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : Union[str, Any] = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` snake_case__ : Any = f"{text_of_1_token} {text_of_1_token}" snake_case__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Tuple = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Optional[Any] = f" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) snake_case__ : Dict = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ) + 1, 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Any = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , )
38
1
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be trained.'''} ) lowerCamelCase__ = field( default='''./''' , metadata={'''help''': '''Save dir where model repo is cloned and models updates are saved to.'''} ) lowerCamelCase__ = field( default='''codeparrot/codeparrot-clean-train''' , metadata={'''help''': '''Name or path of training dataset.'''} ) lowerCamelCase__ = field( default='''codeparrot/codeparrot-clean-valid''' , metadata={'''help''': '''Name or path of validation dataset.'''} ) lowerCamelCase__ = field(default=2 , metadata={'''help''': '''Batch size for training.'''} ) lowerCamelCase__ = field(default=2 , metadata={'''help''': '''Batch size for evaluation.'''} ) lowerCamelCase__ = field(default=0.1 , metadata={'''help''': '''Value of weight decay.'''} ) lowerCamelCase__ = field( default=10_000 , metadata={'''help''': '''Size of buffer used to shuffle streaming dataset.'''} ) lowerCamelCase__ = field(default=2E-4 , metadata={'''help''': '''Learning rate fo training.'''} ) lowerCamelCase__ = field(default='''cosine''' , metadata={'''help''': '''Learning rate.'''} ) lowerCamelCase__ = field( default=750 , metadata={'''help''': '''Number of warmup steps in the learning rate schedule.'''} ) lowerCamelCase__ = field( default=16 , metadata={'''help''': '''Number of gradient accumulation steps.'''} ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Use gradient checkpointing to reduce memory footprint.'''} ) lowerCamelCase__ = field(default=50_000 , metadata={'''help''': '''Maximum number of training steps.'''} ) lowerCamelCase__ = field( default=-1 , metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''} ) lowerCamelCase__ = field(default=1_024 , metadata={'''help''': '''Sequence lengths used for training.'''} ) lowerCamelCase__ = field(default=1 , metadata={'''help''': '''Training seed.'''} ) lowerCamelCase__ = field( default=1_024 , metadata={'''help''': '''Interval to save checkpoints. Measured as number of forward passes not training steps.'''} , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''States path if the training should continue from a checkpoint folder.'''} ) lowerCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''If True the data is pretokenized.'''} ) @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be evaluated.'''} ) lowerCamelCase__ = field( default='''codeparrot/codeparrot-clean-valid''' , metadata={'''help''': '''Name or path of validation dataset.'''} ) lowerCamelCase__ = field(default=2 , metadata={'''help''': '''Batch size used for evaluation.'''} ) lowerCamelCase__ = field( default=-1 , metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''} ) lowerCamelCase__ = field(default=1_024 , metadata={'''help''': '''Length of sequences to be evaluated.'''} ) lowerCamelCase__ = field(default=1 , metadata={'''help''': '''Random seed used for evaluation.'''} ) @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be evaluated.'''} ) lowerCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Number of workers used for code evaluation.'''} ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''The number of human-eval tasks to run. If not included all tasks are evaluated.'''} , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Sample from the language model\'s output distribution.'''} ) lowerCamelCase__ = field(default=0.2 , metadata={'''help''': '''Sampling temperature used for generation.'''} ) lowerCamelCase__ = field(default=256 , metadata={'''help''': '''Maximum number of newly generated tokens.'''} ) lowerCamelCase__ = field(default=0 , metadata={'''help''': '''Top-k parameter used for generation.'''} ) lowerCamelCase__ = field(default=0.9_5 , metadata={'''help''': '''Top-p parameter used for nucleus sampling.'''} ) lowerCamelCase__ = field(default=10 , metadata={'''help''': '''Number of generations to run in parallel.'''} ) lowerCamelCase__ = field( default=200 , metadata={'''help''': '''Number of completions to generate for each sample.'''} ) lowerCamelCase__ = field(default=1 , metadata={'''help''': '''Random seed used for evaluation.'''} ) lowerCamelCase__ = field( default='''eval_results.json''' , metadata={'''help''': '''Random seed used for evaluation.'''} ) lowerCamelCase__ = field( default='''0''' , metadata={'''help''': '''Allow `code_eval` to execute Python code on machine'''} ) lowerCamelCase__ = field( default=-1 , metadata={ '''help''': ( '''Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive''' ''' number corresponds to which GPU device id to run on.''' ) } , ) @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={ '''help''': '''The number of CPU cores to use for parallel preprocessing. Default uses the maximum available.''' } , ) lowerCamelCase__ = field( default='''transformersbook/codeparrot''' , metadata={'''help''': '''Folder or name of dataset to process.'''} ) lowerCamelCase__ = field( default='''codeparrot-clean''' , metadata={'''help''': '''Folder to save processed processed dataset.'''} ) lowerCamelCase__ = field( default=100_000 , metadata={'''help''': '''Number of files to save per JSON output file.'''} ) lowerCamelCase__ = field(default='''content''' , metadata={'''help''': '''Column containing text data to process.'''} ) lowerCamelCase__ = field( default=1_000 , metadata={'''help''': '''Maximum line length in file, otherwise file is filtered.'''} ) lowerCamelCase__ = field( default=100 , metadata={'''help''': '''Maximum mean line length in file, otherwise file is filtered.'''} ) lowerCamelCase__ = field( default=0.2_5 , metadata={'''help''': '''Maximum fraction of non-alphanumeric characters, otherwise file is filtered.'''} ) lowerCamelCase__ = field( default=1.5 , metadata={'''help''': '''Minimum character token ratio for the file, otherwise file is filtered.'''} ) lowerCamelCase__ = field( default=0.7 , metadata={'''help''': '''Probability for filtering config, test and uncommon files.'''} ) lowerCamelCase__ = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Name or path to the tokenizer.'''} , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''If True, near-duplicate samples are removed.'''} ) lowerCamelCase__ = field( default=0.8_5 , metadata={'''help''': '''Jaccard threshold for near-duplicate samples.'''} ) @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default='''gpt2''' , metadata={'''help''': '''Base tokenizer to build new tokenizer from.'''} ) lowerCamelCase__ = field( default='''transformersbook/codeparrot-train''' , metadata={'''help''': '''Dataset to train tokenizer on.'''} ) lowerCamelCase__ = field(default='''content''' , metadata={'''help''': '''Column containing text data to process.'''} ) lowerCamelCase__ = field(default=200_000 , metadata={'''help''': '''Number of examples to train tokenizer on.'''} ) lowerCamelCase__ = field( default=32_768 , metadata={'''help''': '''Number of examples to train the tokenizer on.'''} ) lowerCamelCase__ = field(default='''codeparrot''' , metadata={'''help''': '''Name of new tokenizer.'''} ) lowerCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Push saved tokenizer to the hub.'''} ) @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Name or path to the tokenizer.'''} ) lowerCamelCase__ = field( default='''codeparrot/codeparrot-clean-train''' , metadata={'''help''': '''Name or path to the dataset to pretokenize.'''} ) lowerCamelCase__ = field( default='''tokenized-codeparrot-train''' , metadata={'''help''': '''Repo name of the pretokenized data.'''} ) lowerCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Number of workers used for code evaluation.'''} ) @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default='''gpt2-large''' , metadata={'''help''': '''Configuration to use for model initialization.'''} ) lowerCamelCase__ = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Tokenizer attached to model.'''} ) lowerCamelCase__ = field(default='''codeparrot''' , metadata={'''help''': '''Name of the created model.'''} ) lowerCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Push saved tokenizer to the hub.'''} )
38
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : int = logging.get_logger(__name__) A_ : Any = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''resnet''' lowerCamelCase__ = ['''basic''', '''bottleneck'''] def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , __SCREAMING_SNAKE_CASE=[3, 4, 6, 3] , __SCREAMING_SNAKE_CASE="bottleneck" , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) snake_case__ : List[Any] = num_channels snake_case__ : str = embedding_size snake_case__ : List[Any] = hidden_sizes snake_case__ : Dict = depths snake_case__ : List[Any] = layer_type snake_case__ : int = hidden_act snake_case__ : Union[str, Any] = downsample_in_first_stage snake_case__ : Dict = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] snake_case__ , snake_case__ : Any = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names ) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = version.parse('''1.11''' ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __UpperCamelCase ( self ): return 1e-3
38
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __snake_case ( unittest.TestCase ): '''simple docstring''' @property def __UpperCamelCase ( self ): torch.manual_seed(0 ) snake_case__ : Dict = 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""") , ) return model def __UpperCamelCase ( self ): snake_case__ : Tuple = self.dummy_uncond_unet snake_case__ : int = PNDMScheduler() snake_case__ : int = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = torch.manual_seed(0 ) snake_case__ : Union[str, Any] = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2_0 , output_type="""numpy""" ).images snake_case__ : Tuple = torch.manual_seed(0 ) snake_case__ : Union[str, Any] = pndm(generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2_0 , output_type="""numpy""" , return_dict=__SCREAMING_SNAKE_CASE )[0] snake_case__ : Dict = image[0, -3:, -3:, -1] snake_case__ : List[str] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) snake_case__ : Dict = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Tuple = """google/ddpm-cifar10-32""" snake_case__ : Dict = UNetaDModel.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : str = PNDMScheduler() snake_case__ : Optional[int] = PNDMPipeline(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) pndm.to(__SCREAMING_SNAKE_CASE ) pndm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = torch.manual_seed(0 ) snake_case__ : str = pndm(generator=__SCREAMING_SNAKE_CASE , output_type="""numpy""" ).images snake_case__ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) snake_case__ : Optional[Any] = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
38
'''simple docstring''' # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( "pipelines_utils", "0.22.0", "Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.", standard_warn=False, stacklevel=3, )
38
1
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : List[str] = inspect.getfile(accelerate.test_utils ) snake_case__ : Any = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) snake_case__ : List[str] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) snake_case__ : Optional[int] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def __UpperCamelCase ( self ): print(f"Found {torch.cuda.device_count()} devices." ) snake_case__ : List[Any] = ["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def __UpperCamelCase ( self ): print(f"Found {torch.cuda.device_count()} devices." ) snake_case__ : Union[str, Any] = ["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", self.operation_file_path] print(f"Command: {cmd}" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def __UpperCamelCase ( self ): snake_case__ : Tuple = ["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def __UpperCamelCase ( self ): print(f"Found {torch.cuda.device_count()} devices, using 2 devices only" ) snake_case__ : Optional[Any] = ["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) if __name__ == "__main__": A_ : Union[str, Any] = Accelerator() A_ : List[Any] = (accelerator.state.process_index + 2, 10) A_ : Tuple = torch.randint(0, 10, shape).to(accelerator.device) A_ : List[Any] = "" A_ : Any = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." A_ : Any = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." A_ : Optional[Any] = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
38
'''simple docstring''' import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self ): snake_case__ : str = [] def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_init_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_train_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_train_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_epoch_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_epoch_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_step_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_step_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_evaluate""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_predict""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_save""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_log""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_prediction_step""" ) @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Tuple = tempfile.mkdtemp() def __UpperCamelCase ( self ): shutil.rmtree(self.output_dir ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=False , **__SCREAMING_SNAKE_CASE ): # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. snake_case__ : List[Any] = RegressionDataset(length=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionDataset(length=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionModelConfig(a=__SCREAMING_SNAKE_CASE , b=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionPreTrainedModel(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = TrainingArguments(self.output_dir , disable_tqdm=__SCREAMING_SNAKE_CASE , report_to=[] , **__SCREAMING_SNAKE_CASE ) return Trainer( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , train_dataset=__SCREAMING_SNAKE_CASE , eval_dataset=__SCREAMING_SNAKE_CASE , callbacks=__SCREAMING_SNAKE_CASE , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) # Order doesn't matter snake_case__ : Tuple = sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : cb.__name__ if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else cb.__class__.__name__ ) snake_case__ : List[str] = sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : cb.__name__ if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else cb.__class__.__name__ ) for cba, cba in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(__SCREAMING_SNAKE_CASE , cba.__class__ ) elif not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(cba.__class__ , __SCREAMING_SNAKE_CASE ) else: self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = ["""on_init_end""", """on_train_begin"""] snake_case__ : Union[str, Any] = 0 snake_case__ : Dict = len(trainer.get_eval_dataloader() ) snake_case__ : Any = ["""on_prediction_step"""] * len(trainer.get_eval_dataloader() ) + ["""on_log""", """on_evaluate"""] for _ in range(trainer.state.num_train_epochs ): expected_events.append("""on_epoch_begin""" ) for _ in range(__SCREAMING_SNAKE_CASE ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append("""on_log""" ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append("""on_save""" ) expected_events.append("""on_epoch_end""" ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __UpperCamelCase ( self ): snake_case__ : Any = self.get_trainer() snake_case__ : str = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # Callbacks passed at init are added to the default callbacks snake_case__ : List[str] = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback snake_case__ : Optional[Any] = self.get_trainer(disable_tqdm=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = DEFAULT_CALLBACKS.copy() + [ProgressCallback] snake_case__ : int = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.remove(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = self.get_trainer() snake_case__ : List[str] = trainer.pop_callback(__SCREAMING_SNAKE_CASE ) self.assertEqual(cb.__class__ , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) trainer.add_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.insert(0 , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # We can also add, pop, or remove by instance snake_case__ : List[Any] = self.get_trainer() snake_case__ : List[str] = trainer.callback_handler.callbacks[0] trainer.remove_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.remove(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = self.get_trainer() snake_case__ : Any = trainer.callback_handler.callbacks[0] snake_case__ : Optional[Any] = trainer.pop_callback(__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) trainer.add_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.insert(0 , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action="""ignore""" , category=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # Independent log/save/eval snake_case__ : Dict = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() snake_case__ : int = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Any = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Tuple = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy="""steps""" ) trainer.train() snake_case__ : str = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Tuple = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy="""epoch""" ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # A bit of everything snake_case__ : Dict = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=1_0 , eval_steps=5 , evaluation_strategy="""steps""" , ) trainer.train() snake_case__ : Tuple = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # warning should be emitted for duplicated callbacks with patch("""transformers.trainer_callback.logger.warning""" ) as warn_mock: snake_case__ : List[str] = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(__SCREAMING_SNAKE_CASE ) in warn_mock.call_args[0][0]
38
1
'''simple docstring''' from __future__ import annotations import requests A_ : Optional[int] = set( "approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports".split() ) def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : int = 1 , __magic_name__ : str = "new" , __magic_name__ : list | None = None ) -> dict: '''simple docstring''' snake_case__ : Optional[Any] = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(__magic_name__ ) - valid_terms ) ): snake_case__ : Dict = f"Invalid search term: {invalid_search_terms}" raise ValueError(__magic_name__ ) snake_case__ : Tuple = requests.get( f"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}" , headers={"""User-agent""": """A random string"""} , ) if response.status_code == 4_29: raise requests.HTTPError snake_case__ : Optional[int] = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(__magic_name__ )} snake_case__ : Optional[Any] = {} for id_ in range(__magic_name__ ): snake_case__ : List[str] = { item: data["""data"""]["""children"""][id_]["""data"""][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
38
'''simple docstring''' import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision 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 DPTImageProcessor class __snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=1_8 , __SCREAMING_SNAKE_CASE=3_0 , __SCREAMING_SNAKE_CASE=4_0_0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ): snake_case__ : Any = size if size is not None else {"""height""": 1_8, """width""": 1_8} snake_case__ : List[Any] = parent snake_case__ : int = batch_size snake_case__ : List[Any] = num_channels snake_case__ : str = image_size snake_case__ : Union[str, Any] = min_resolution snake_case__ : List[Any] = max_resolution snake_case__ : Tuple = do_resize snake_case__ : int = size snake_case__ : Tuple = do_normalize snake_case__ : Dict = image_mean snake_case__ : Union[str, Any] = image_std def __UpperCamelCase ( self ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = DPTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self ): snake_case__ : str = DPTImageProcessingTester(self ) @property def __UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_std""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """size""" ) ) def __UpperCamelCase ( self ): snake_case__ : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 1_8, """width""": 1_8} ) snake_case__ : List[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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input snake_case__ : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case__ : List[str] = image_processing(__SCREAMING_SNAKE_CASE , 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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case__ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input snake_case__ : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case__ : Any = image_processing(__SCREAMING_SNAKE_CASE , 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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case__ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input snake_case__ : List[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 snake_case__ : List[str] = image_processing(__SCREAMING_SNAKE_CASE , 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"""], ) , )
38
1
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : list[str] ) -> str: '''simple docstring''' snake_case__ : List[Any] = """""" for word_or_phrase in separated: if not isinstance(__magic_name__ , __magic_name__ ): raise Exception("""join() accepts only strings to be joined""" ) joined += word_or_phrase + separator return joined.strip(__magic_name__ ) if __name__ == "__main__": from doctest import testmod testmod()
38
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig 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 TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Dict = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """embed_dim""" ) ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """num_heads""" ) ) class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=[1_6, 4_8, 9_6] , __SCREAMING_SNAKE_CASE=[1, 3, 6] , __SCREAMING_SNAKE_CASE=[1, 2, 1_0] , __SCREAMING_SNAKE_CASE=[7, 3, 3] , __SCREAMING_SNAKE_CASE=[4, 2, 2] , __SCREAMING_SNAKE_CASE=[2, 1, 1] , __SCREAMING_SNAKE_CASE=[2, 2, 2] , __SCREAMING_SNAKE_CASE=[False, False, True] , __SCREAMING_SNAKE_CASE=[0.0, 0.0, 0.0] , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=2 , ): snake_case__ : List[str] = parent snake_case__ : Tuple = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : List[Any] = patch_sizes snake_case__ : Optional[int] = patch_stride snake_case__ : Optional[Any] = patch_padding snake_case__ : Any = is_training snake_case__ : int = use_labels snake_case__ : Dict = num_labels snake_case__ : Optional[Any] = num_channels snake_case__ : Optional[Any] = embed_dim snake_case__ : Optional[int] = num_heads snake_case__ : Optional[int] = stride_kv snake_case__ : int = depth snake_case__ : Optional[Any] = cls_token snake_case__ : List[Any] = attention_drop_rate snake_case__ : Union[str, Any] = initializer_range snake_case__ : List[Any] = layer_norm_eps def __UpperCamelCase ( self ): snake_case__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[Any] = None if self.use_labels: # create a random int32 tensor of given shape snake_case__ : List[str] = ids_tensor([self.batch_size] , self.num_labels ) snake_case__ : List[str] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = TFCvtModel(config=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = model(__SCREAMING_SNAKE_CASE , training=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = (self.image_size, self.image_size) snake_case__ , snake_case__ : str = image_size[0], image_size[1] for i in range(len(self.depth ) ): snake_case__ : Any = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) snake_case__ : Optional[int] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = self.num_labels snake_case__ : str = TFCvtForImageClassification(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , training=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Union[str, Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () lowerCamelCase__ = ( {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification} if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = TFCvtModelTester(self ) snake_case__ : Any = TFCvtConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason="""Cvt does not output attentions""" ) def __UpperCamelCase ( self ): pass @unittest.skip(reason="""Cvt does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass @unittest.skip(reason="""Cvt does not support input and output embeddings""" ) def __UpperCamelCase ( self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) def __UpperCamelCase ( self ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def __UpperCamelCase ( self ): super().test_keras_fit() @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""" ) def __UpperCamelCase ( self ): snake_case__ : List[str] = tf.keras.mixed_precision.Policy("""mixed_float16""" ) tf.keras.mixed_precision.set_global_policy(__SCREAMING_SNAKE_CASE ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("""float32""" ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Optional[Any] = [*signature.parameters.keys()] snake_case__ : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): def check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[int] = outputs.hidden_states snake_case__ : Tuple = len(self.model_tester.depth ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : List[Any] = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[str] = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def __UpperCamelCase ( self ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : str = TFCvtModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class __snake_case ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCamelCase ( self ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) snake_case__ : Union[str, Any] = self.default_image_processor snake_case__ : int = prepare_img() snake_case__ : Dict = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) # forward pass snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE ) # verify the logits snake_case__ : str = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : int = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
1
'''simple docstring''' def UpperCamelCase__ ( ) -> list[list[int]]: '''simple docstring''' return [list(range(10_00 - i , -10_00 - i , -1 ) ) for i in range(10_00 )] A_ : Any = generate_large_matrix() A_ : str = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def UpperCamelCase__ ( __magic_name__ : list[list[int]] ) -> None: '''simple docstring''' assert all(row == sorted(__magic_name__ , reverse=__magic_name__ ) for row in grid ) assert all(list(__magic_name__ ) == sorted(__magic_name__ , reverse=__magic_name__ ) for col in zip(*__magic_name__ ) ) def UpperCamelCase__ ( __magic_name__ : list[int] ) -> int: '''simple docstring''' snake_case__ : Dict = 0 snake_case__ : Tuple = len(__magic_name__ ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: snake_case__ : Optional[Any] = (left + right) // 2 snake_case__ : List[Any] = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: snake_case__ : str = mid + 1 else: snake_case__ : str = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : list[list[int]] ) -> int: '''simple docstring''' snake_case__ : Dict = 0 snake_case__ : Any = len(grid[0] ) for i in range(len(__magic_name__ ) ): snake_case__ : int = find_negative_index(grid[i][:bound] ) total += bound return (len(__magic_name__ ) * len(grid[0] )) - total def UpperCamelCase__ ( __magic_name__ : list[list[int]] ) -> int: '''simple docstring''' return len([number for row in grid for number in row if number < 0] ) def UpperCamelCase__ ( __magic_name__ : list[list[int]] ) -> int: '''simple docstring''' snake_case__ : List[str] = 0 for row in grid: for i, number in enumerate(__magic_name__ ): if number < 0: total += len(__magic_name__ ) - i break return total def UpperCamelCase__ ( ) -> None: '''simple docstring''' from timeit import timeit print("""Running benchmarks""" ) snake_case__ : Tuple = ( """from __main__ import count_negatives_binary_search, """ """count_negatives_brute_force, count_negatives_brute_force_with_break, grid""" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): snake_case__ : Union[str, Any] = timeit(f"{func}(grid=grid)" , setup=__magic_name__ , number=5_00 ) print(f"{func}() took {time:0.4f} seconds" ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
38
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. snake_case__ : int = [[1, 2, 4], [1, 2, 3, 4]] snake_case__ : Any = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) self.assertTrue(isinstance(dc.token_ids , __SCREAMING_SNAKE_CASE ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __UpperCamelCase ( self ): # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). snake_case__ : Union[str, Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) # fails here def __UpperCamelCase ( self ): snake_case__ : List[str] = [[1, 2, 3], [1, 2, 4]] snake_case__ : Optional[int] = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ , snake_case__ : Any = dc.update(1 ) snake_case__ : Any = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : Tuple = dc.update(2 ) snake_case__ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = dc.update(3 ) snake_case__ : List[str] = stepped is True and completed is True and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] snake_case__ : int = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ , snake_case__ : str = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : Dict = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
38
1
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: '''simple docstring''' snake_case__ : Tuple = set() # Replace all the whitespace in our sentence snake_case__ : List[Any] = input_str.replace(""" """ , """""" ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(__magic_name__ ) == 26 def UpperCamelCase__ ( __magic_name__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: '''simple docstring''' snake_case__ : Optional[Any] = [False] * 26 for char in input_str: if char.islower(): snake_case__ : int = True elif char.isupper(): snake_case__ : Optional[Any] = True return all(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : str = "The quick brown fox jumps over the lazy dog" , ) -> bool: '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def UpperCamelCase__ ( ) -> None: '''simple docstring''' from timeit import timeit snake_case__ : Optional[Any] = """from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest""" print(timeit("""is_pangram()""" , setup=__magic_name__ ) ) print(timeit("""is_pangram_faster()""" , setup=__magic_name__ ) ) print(timeit("""is_pangram_fastest()""" , setup=__magic_name__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
38
'''simple docstring''' import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[int] = logging.get_logger(__name__) A_ : Tuple = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''segformer''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=[2, 2, 2, 2] , __SCREAMING_SNAKE_CASE=[8, 4, 2, 1] , __SCREAMING_SNAKE_CASE=[3_2, 6_4, 1_6_0, 2_5_6] , __SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , __SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , __SCREAMING_SNAKE_CASE=[1, 2, 5, 8] , __SCREAMING_SNAKE_CASE=[4, 4, 4, 4] , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1e-6 , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=2_5_5 , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , __SCREAMING_SNAKE_CASE , ) snake_case__ : Dict = num_channels snake_case__ : Optional[Any] = num_encoder_blocks snake_case__ : Any = depths snake_case__ : Optional[int] = sr_ratios snake_case__ : Tuple = hidden_sizes snake_case__ : List[str] = patch_sizes snake_case__ : str = strides snake_case__ : Optional[int] = mlp_ratios snake_case__ : Optional[Any] = num_attention_heads snake_case__ : Dict = hidden_act snake_case__ : Optional[int] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : List[Any] = classifier_dropout_prob snake_case__ : int = initializer_range snake_case__ : List[str] = drop_path_rate snake_case__ : int = layer_norm_eps snake_case__ : List[Any] = decoder_hidden_size snake_case__ : List[Any] = kwargs.get("""reshape_last_stage""" , __SCREAMING_SNAKE_CASE ) snake_case__ : Dict = semantic_loss_ignore_index class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = version.parse('''1.11''' ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __UpperCamelCase ( self ): return 1e-4 @property def __UpperCamelCase ( self ): return 1_2
38
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class __snake_case ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ViTImageProcessor if is_vision_available() else None @property def __UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = (3, 3_2, 1_2_8) snake_case__ : List[Any] = tempfile.mkdtemp() # fmt: off snake_case__ : str = ["""[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 snake_case__ : List[str] = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) snake_case__ : Optional[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(__SCREAMING_SNAKE_CASE ) + """\n""" ) snake_case__ : Optional[int] = { """do_normalize""": False, """do_resize""": True, """image_processor_type""": """ViTImageProcessor""", """resample""": 3, """size""": {"""height""": 3_2, """width""": 1_2_8}, } snake_case__ : str = os.path.join(self.tmpdirname , __SCREAMING_SNAKE_CASE ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): return MgpstrTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): shutil.rmtree(self.tmpdirname ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta ) snake_case__ : List[str] = Image.fromarray(np.moveaxis(__SCREAMING_SNAKE_CASE , 0 , -1 ) ) return image_input def __UpperCamelCase ( self ): snake_case__ : List[str] = self.get_tokenizer() snake_case__ : Union[str, Any] = self.get_image_processor() snake_case__ : Optional[int] = MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) snake_case__ : Tuple = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : int = self.get_tokenizer() snake_case__ : Union[str, Any] = self.get_image_processor() snake_case__ : Optional[int] = MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) snake_case__ : str = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) snake_case__ : List[Any] = self.get_image_processor(do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) snake_case__ : Optional[int] = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=__SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , __SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.get_image_processor() snake_case__ : Tuple = self.get_tokenizer() snake_case__ : Optional[Any] = MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.prepare_image_inputs() snake_case__ : Tuple = image_processor(__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) snake_case__ : Optional[int] = processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __UpperCamelCase ( self ): snake_case__ : Dict = self.get_image_processor() snake_case__ : Union[str, Any] = self.get_tokenizer() snake_case__ : int = MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = """test""" snake_case__ : Optional[Any] = processor(text=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = tokenizer(__SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.get_image_processor() snake_case__ : List[Any] = self.get_tokenizer() snake_case__ : Any = MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) snake_case__ : int = """test""" snake_case__ : Any = self.prepare_image_inputs() snake_case__ : Union[str, Any] = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """labels"""] ) # test if it raises when no input is passed with pytest.raises(__SCREAMING_SNAKE_CASE ): processor() def __UpperCamelCase ( self ): snake_case__ : List[str] = self.get_image_processor() snake_case__ : Optional[Any] = self.get_tokenizer() snake_case__ : List[str] = MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) snake_case__ : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] snake_case__ : Any = processor.char_decode(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = [seq.replace(""" """ , """""" ) for seq in decoded_tok] self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[str] = self.get_image_processor() snake_case__ : str = self.get_tokenizer() snake_case__ : Optional[int] = MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) snake_case__ : int = None snake_case__ : Optional[int] = self.prepare_image_inputs() snake_case__ : List[Any] = processor(text=__SCREAMING_SNAKE_CASE , images=__SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.get_image_processor() snake_case__ : List[Any] = self.get_tokenizer() snake_case__ : Optional[Any] = MgpstrProcessor(tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) snake_case__ : str = torch.randn(1 , 2_7 , 3_8 ) snake_case__ : Dict = torch.randn(1 , 2_7 , 5_0_2_5_7 ) snake_case__ : Union[str, Any] = torch.randn(1 , 2_7 , 3_0_5_2_2 ) snake_case__ : List[str] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ["""generated_text""", """scores""", """char_preds""", """bpe_preds""", """wp_preds"""] )
38
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : List[Any]=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : str = None if token is not None: snake_case__ : str = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : List[Any] = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" snake_case__ : str = requests.get(__magic_name__ , headers=__magic_name__ ).json() snake_case__ : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) snake_case__ : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(__magic_name__ ): snake_case__ : Tuple = requests.get(url + f"&page={i + 2}" , headers=__magic_name__ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any]=None ) -> List[str]: '''simple docstring''' snake_case__ : Optional[Any] = None if token is not None: snake_case__ : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : Dict = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" snake_case__ : Union[str, Any] = requests.get(__magic_name__ , headers=__magic_name__ ).json() snake_case__ : Dict = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) snake_case__ : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(__magic_name__ ): snake_case__ : Dict = requests.get(url + f"&page={i + 2}" , headers=__magic_name__ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Dict ) -> Dict: '''simple docstring''' snake_case__ : Optional[Any] = None if token is not None: snake_case__ : Dict = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : str = requests.get(__magic_name__ , headers=__magic_name__ , allow_redirects=__magic_name__ ) snake_case__ : Any = result.headers["""Location"""] snake_case__ : Tuple = requests.get(__magic_name__ , allow_redirects=__magic_name__ ) snake_case__ : int = os.path.join(__magic_name__ , f"{artifact_name}.zip" ) with open(__magic_name__ , """wb""" ) as fp: fp.write(response.content ) def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : str=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Any = [] snake_case__ : Union[str, Any] = [] snake_case__ : Any = None with zipfile.ZipFile(__magic_name__ ) as z: for filename in z.namelist(): if not os.path.isdir(__magic_name__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(__magic_name__ ) as f: for line in f: snake_case__ : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs snake_case__ : str = line[: line.index(""": """ )] snake_case__ : Optional[int] = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed snake_case__ : Dict = line[len("""FAILED """ ) :] failed_tests.append(__magic_name__ ) elif filename == "job_name.txt": snake_case__ : Optional[Any] = line if len(__magic_name__ ) != len(__magic_name__ ): raise ValueError( f"`errors` and `failed_tests` should have the same number of elements. Got {len(__magic_name__ )} for `errors` " f"and {len(__magic_name__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" """ problem.""" ) snake_case__ : Optional[Any] = None if job_name and job_links: snake_case__ : Optional[Any] = job_links.get(__magic_name__ , __magic_name__ ) # A list with elements of the form (line of error, error, failed test) snake_case__ : List[Any] = [x + [y] + [job_link] for x, y in zip(__magic_name__ , __magic_name__ )] return result def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : Union[str, Any]=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : str = [] snake_case__ : Dict = [os.path.join(__magic_name__ , __magic_name__ ) for p in os.listdir(__magic_name__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(__magic_name__ , job_links=__magic_name__ ) ) return errors def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : str=None ) -> List[Any]: '''simple docstring''' snake_case__ : Any = Counter() counter.update([x[1] for x in logs] ) snake_case__ : Dict = counter.most_common() snake_case__ : Any = {} for error, count in counts: if error_filter is None or error not in error_filter: snake_case__ : int = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} snake_case__ : Union[str, Any] = dict(sorted(r.items() , key=lambda __magic_name__ : item[1]["count"] , reverse=__magic_name__ ) ) return r def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> List[Any]: '''simple docstring''' snake_case__ : str = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): snake_case__ : Tuple = test.split("""/""" )[2] else: snake_case__ : Any = None return test def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : Union[str, Any]=None ) -> List[str]: '''simple docstring''' snake_case__ : List[str] = [(x[0], x[1], get_model(x[2] )) for x in logs] snake_case__ : List[Any] = [x for x in logs if x[2] is not None] snake_case__ : Any = {x[2] for x in logs} snake_case__ : Optional[Any] = {} for test in tests: snake_case__ : str = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) snake_case__ : Optional[int] = counter.most_common() snake_case__ : Optional[int] = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} snake_case__ : int = sum(error_counts.values() ) if n_errors > 0: snake_case__ : str = {"""count""": n_errors, """errors""": error_counts} snake_case__ : Union[str, Any] = dict(sorted(r.items() , key=lambda __magic_name__ : item[1]["count"] , reverse=__magic_name__ ) ) return r def UpperCamelCase__ ( __magic_name__ : int ) -> Optional[int]: '''simple docstring''' snake_case__ : Optional[Any] = """| no. | error | status |""" snake_case__ : int = """|-:|:-|:-|""" snake_case__ : int = [header, sep] for error in reduced_by_error: snake_case__ : Union[str, Any] = reduced_by_error[error]["""count"""] snake_case__ : Dict = f"| {count} | {error[:1_00]} | |" lines.append(__magic_name__ ) return "\n".join(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> List[Any]: '''simple docstring''' snake_case__ : List[Any] = """| model | no. of errors | major error | count |""" snake_case__ : Optional[int] = """|-:|-:|-:|-:|""" snake_case__ : Dict = [header, sep] for model in reduced_by_model: snake_case__ : Tuple = reduced_by_model[model]["""count"""] snake_case__ , snake_case__ : Tuple = list(reduced_by_model[model]["""errors"""].items() )[0] snake_case__ : Optional[int] = f"| {model} | {count} | {error[:60]} | {_count} |" lines.append(__magic_name__ ) return "\n".join(__magic_name__ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") A_ : int = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) A_ : Optional[int] = get_job_links(args.workflow_run_id, token=args.token) A_ : Optional[Any] = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: A_ : int = k.find(" / ") A_ : List[Any] = k[index + len(" / ") :] A_ : List[str] = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) A_ : int = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) A_ : str = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error A_ : List[str] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors A_ : Any = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) A_ : Any = reduce_by_error(errors) A_ : Union[str, Any] = reduce_by_model(errors) A_ : Any = make_github_table(reduced_by_error) A_ : Optional[Any] = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
38
1
'''simple docstring''' import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="resnet50" , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , ): snake_case__ : List[str] = parent snake_case__ : List[Any] = out_indices if out_indices is not None else [4] snake_case__ : Any = stage_names snake_case__ : Union[str, Any] = out_features snake_case__ : List[str] = backbone snake_case__ : Any = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : Any = num_channels snake_case__ : Union[str, Any] = use_pretrained_backbone snake_case__ : Any = is_training def __UpperCamelCase ( self ): snake_case__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : Any = self.get_config() return config, pixel_values def __UpperCamelCase ( self ): return TimmBackboneConfig( image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = TimmBackbone(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): snake_case__ : List[Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 1_4, 1_4) , ) def __UpperCamelCase ( self ): snake_case__ : Any = self.prepare_config_and_inputs() snake_case__ , snake_case__ : List[str] = config_and_inputs snake_case__ : List[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch @require_timm class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (TimmBackbone,) if is_torch_available() else () lowerCamelCase__ = {'''feature-extraction''': TimmBackbone} if is_torch_available() else {} lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : Tuple = TimmBackboneModelTester(self ) snake_case__ : int = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = """resnet18""" snake_case__ : Optional[int] = """microsoft/resnet-18""" snake_case__ : List[Any] = AutoBackbone.from_pretrained(__SCREAMING_SNAKE_CASE , use_timm_backbone=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = AutoBackbone.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ) , len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices , (-1,) ) self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names ) - 1] ) snake_case__ : int = AutoBackbone.from_pretrained(__SCREAMING_SNAKE_CASE , use_timm_backbone=__SCREAMING_SNAKE_CASE , out_indices=[1, 2, 3] ) snake_case__ : Optional[Any] = AutoBackbone.from_pretrained(__SCREAMING_SNAKE_CASE , out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices , transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ) , len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels , transformers_model.channels ) @unittest.skip("""TimmBackbone doesn't support feed forward chunking""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""TimmBackbone doesn't have num_hidden_layers attribute""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""TimmBackbone initialization is managed on the timm side""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""TimmBackbone models doesn't have inputs_embeds""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""model weights aren't tied in TimmBackbone.""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""model weights aren't tied in TimmBackbone.""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""TimmBackbone doesn't have hidden size info in its configuration.""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""TimmBackbone doesn't support output_attentions.""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""Safetensors is not supported by timm.""" ) def __UpperCamelCase ( self ): pass @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Union[str, Any] = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Tuple = [*signature.parameters.keys()] snake_case__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : str = True snake_case__ : List[str] = self.has_attentions # no need to test all models as different heads yield the same functionality snake_case__ : Optional[int] = self.all_model_classes[0] snake_case__ : Optional[int] = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : int = model(**__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = outputs[0][-1] # Encoder-/Decoder-only models snake_case__ : int = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: snake_case__ : Optional[Any] = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Optional[int] = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : List[Any] = model(**__SCREAMING_SNAKE_CASE ) self.assertEqual(len(result.feature_maps ) , len(config.out_indices ) ) self.assertEqual(len(model.channels ) , len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None snake_case__ : Any = copy.deepcopy(__SCREAMING_SNAKE_CASE ) snake_case__ : str = None snake_case__ : List[Any] = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Any = model(**__SCREAMING_SNAKE_CASE ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights snake_case__ : Union[str, Any] = copy.deepcopy(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = False snake_case__ : List[str] = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Union[str, Any] = model(**__SCREAMING_SNAKE_CASE )
38
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version A_ : Tuple = get_logger(__name__) class __snake_case : '''simple docstring''' lowerCamelCase__ = '''dummy_data''' lowerCamelCase__ = '''datasets''' lowerCamelCase__ = False def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , ): snake_case__ : List[Any] = 0 snake_case__ : Union[str, Any] = dataset_name snake_case__ : Optional[int] = cache_dir snake_case__ : Union[str, Any] = use_local_dummy_data snake_case__ : int = config # download_callbacks take a single url as input snake_case__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root snake_case__ : Union[str, Any] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general snake_case__ : Union[str, Any] = str(__SCREAMING_SNAKE_CASE ) # to be downloaded snake_case__ : List[str] = None snake_case__ : List[str] = None @property def __UpperCamelCase ( self ): if self._dummy_file is None: snake_case__ : List[str] = self.download_dummy_data() return self._dummy_file @property def __UpperCamelCase ( self ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("""dummy""" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("""dummy""" , self.version_name ) @property def __UpperCamelCase ( self ): return os.path.join(self.dummy_data_folder , """dummy_data.zip""" ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) snake_case__ : Optional[int] = cached_path( __SCREAMING_SNAKE_CASE , cache_dir=self.cache_dir , extract_compressed_file=__SCREAMING_SNAKE_CASE , force_extract=__SCREAMING_SNAKE_CASE ) return os.path.join(__SCREAMING_SNAKE_CASE , self.dummy_file_name ) @property def __UpperCamelCase ( self ): return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __UpperCamelCase ( self ): if self._bucket_url is None: snake_case__ : List[str] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , """/""" ) ) return self._bucket_url @property def __UpperCamelCase ( self ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , """/""" ).split("""/""" )[:-1] ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): if self.load_existing_dummy_data: # dummy data is downloaded and tested snake_case__ : List[Any] = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned snake_case__ : List[Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return self.create_dummy_data_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ): return self.create_dummy_data_list(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return self.create_dummy_data_single(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): return self.download_and_extract(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return self.download_and_extract(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): return path def __UpperCamelCase ( self ): return {} def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for single_url in single_urls: download_callback(__SCREAMING_SNAKE_CASE ) else: snake_case__ : List[str] = single_urls download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = [os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(Path(__SCREAMING_SNAKE_CASE ).name ) ) for x in single_urls] else: snake_case__ : List[Any] = single_urls snake_case__ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(Path(__SCREAMING_SNAKE_CASE ).name ) ) snake_case__ : Optional[int] = value # make sure that values are unique if all(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique snake_case__ : List[Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one snake_case__ : Tuple = all(bool(re.findall("""[0-9]{3,}-of-[0-9]{3,}""" , __SCREAMING_SNAKE_CASE ) ) for url in data_url ) snake_case__ : List[Any] = all( url.startswith("""https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed""" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): snake_case__ : List[str] = [data_url[0]] * len(__SCREAMING_SNAKE_CASE ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case__ : List[Any] = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(single_url.split("""/""" )[-1] ) ) dummy_data_list.append(__SCREAMING_SNAKE_CASE ) return dummy_data_list def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for download_callback in self.download_callbacks: download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case__ : Any = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(data_url.split("""/""" )[-1] ) ) if os.path.exists(__SCREAMING_SNAKE_CASE ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): def _iter_archive_members(__SCREAMING_SNAKE_CASE ): # this preserves the order of the members inside the ZIP archive snake_case__ : List[str] = Path(self.dummy_file ).parent snake_case__ : Dict = path.relative_to(__SCREAMING_SNAKE_CASE ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: snake_case__ : Optional[int] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = Path(__SCREAMING_SNAKE_CASE ) snake_case__ : int = _iter_archive_members(__SCREAMING_SNAKE_CASE ) if self.use_local_dummy_data else path.rglob("""*""" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((""".""", """__""") ): yield file_path.relative_to(__SCREAMING_SNAKE_CASE ).as_posix(), file_path.open("""rb""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[int] = [paths] for path in paths: if os.path.isfile(__SCREAMING_SNAKE_CASE ): if os.path.basename(__SCREAMING_SNAKE_CASE ).startswith((""".""", """__""") ): return yield path else: for dirpath, dirnames, filenames in os.walk(__SCREAMING_SNAKE_CASE ): if os.path.basename(__SCREAMING_SNAKE_CASE ).startswith((""".""", """__""") ): continue dirnames.sort() for filename in sorted(__SCREAMING_SNAKE_CASE ): if filename.startswith((""".""", """__""") ): continue yield os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
38
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : List[Any] = logging.get_logger(__name__) A_ : Union[str, Any] = { "microsoft/swinv2-tiny-patch4-window8-256": ( "https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json" ), } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''swinv2''' lowerCamelCase__ = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=2_2_4 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=9_6 , __SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , __SCREAMING_SNAKE_CASE=[3, 6, 1_2, 2_4] , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=4.0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-5 , __SCREAMING_SNAKE_CASE=3_2 , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = image_size snake_case__ : Any = patch_size snake_case__ : str = num_channels snake_case__ : Tuple = embed_dim snake_case__ : Optional[int] = depths snake_case__ : List[Any] = len(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = num_heads snake_case__ : int = window_size snake_case__ : List[Any] = mlp_ratio snake_case__ : Dict = qkv_bias snake_case__ : Any = hidden_dropout_prob snake_case__ : List[Any] = attention_probs_dropout_prob snake_case__ : Any = drop_path_rate snake_case__ : str = hidden_act snake_case__ : Dict = use_absolute_embeddings snake_case__ : Any = layer_norm_eps snake_case__ : Dict = initializer_range snake_case__ : Optional[int] = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model snake_case__ : Any = int(embed_dim * 2 ** (len(__SCREAMING_SNAKE_CASE ) - 1) ) snake_case__ : Tuple = (0, 0, 0, 0)
38
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = IFImgaImgSuperResolutionPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def __UpperCamelCase ( self ): return self._get_superresolution_dummy_components() def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): snake_case__ : List[Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case__ : Tuple = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = floats_tensor((1, 3, 1_6, 1_6) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : int = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __UpperCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __UpperCamelCase ( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __UpperCamelCase ( self ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def __UpperCamelCase ( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __UpperCamelCase ( self ): self._test_save_load_local() def __UpperCamelCase ( self ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
38
1
'''simple docstring''' from torch import nn def UpperCamelCase__ ( __magic_name__ : Dict ) -> Optional[int]: '''simple docstring''' if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(f"Unsupported activation function: {act_fn}" )
38
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu A_ : Dict = [ "EAGER", "AOT_EAGER", "INDUCTOR", "NVFUSER", "AOT_NVFUSER", "AOT_CUDAGRAPHS", "OFI", "FX2TRT", "ONNXRT", "IPEX", ] def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : List[Any]=None , __magic_name__ : List[str]=None , __magic_name__ : List[str]=None ) -> Dict: '''simple docstring''' snake_case__ : Optional[int] = True while ask_again: snake_case__ : Optional[Any] = input(__magic_name__ ) try: if default is not None and len(__magic_name__ ) == 0: return default return convert_value(__magic_name__ ) if convert_value is not None else result except Exception: if error_message is not None: print(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Any=[] , __magic_name__ : Optional[int]=None , __magic_name__ : int=0 ) -> Optional[int]: '''simple docstring''' snake_case__ : Union[str, Any] = BulletMenu(__magic_name__ , __magic_name__ ) snake_case__ : Optional[Any] = menu.run(default_choice=__magic_name__ ) return convert_value(__magic_name__ ) if convert_value is not None else result def UpperCamelCase__ ( __magic_name__ : Any ) -> int: '''simple docstring''' snake_case__ : Tuple = int(__magic_name__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def UpperCamelCase__ ( __magic_name__ : str ) -> Tuple: '''simple docstring''' snake_case__ : List[Any] = int(__magic_name__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> List[Any]: '''simple docstring''' snake_case__ : Union[str, Any] = int(__magic_name__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def UpperCamelCase__ ( __magic_name__ : List[str] ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Optional[Any] = int(__magic_name__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> List[Any]: '''simple docstring''' snake_case__ : Optional[Any] = int(__magic_name__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> Tuple: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class __snake_case ( argparse.RawDescriptionHelpFormatter ): '''simple docstring''' def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : str = usage.replace("""<command> [<args>] """ , """""" ) return usage
38
1
'''simple docstring''' # Algorithm for the pigeonhole sorting def UpperCamelCase__ ( __magic_name__ : List[str] ) -> str: '''simple docstring''' snake_case__ : Union[str, Any] = min(__magic_name__ ) # min() finds the minimum value snake_case__ : int = max(__magic_name__ ) # max() finds the maximum value snake_case__ : Any = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size snake_case__ : List[str] = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(__magic_name__ , __magic_name__ ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. snake_case__ : Any = 0 for count in range(__magic_name__ ): while holes[count] > 0: holes[count] -= 1 snake_case__ : Union[str, Any] = count + min_val i += 1 def UpperCamelCase__ ( ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Dict = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(__magic_name__ ) print("""Sorted order is:""" , """ """.join(__magic_name__ ) ) if __name__ == "__main__": main()
38
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( __magic_name__ : list ) -> float: '''simple docstring''' if not nums: raise ValueError("""List is empty""" ) return sum(__magic_name__ ) / len(__magic_name__ ) if __name__ == "__main__": import doctest doctest.testmod()
38
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 DetaImageProcessor class __snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3_0 , __SCREAMING_SNAKE_CASE=4_0_0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=1 / 2_5_5 , __SCREAMING_SNAKE_CASE=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p snake_case__ : Optional[int] = size if size is not None else {"""shortest_edge""": 1_8, """longest_edge""": 1_3_3_3} snake_case__ : str = parent snake_case__ : str = batch_size snake_case__ : Tuple = num_channels snake_case__ : List[Any] = min_resolution snake_case__ : Union[str, Any] = max_resolution snake_case__ : Tuple = do_resize snake_case__ : List[Any] = size snake_case__ : str = do_normalize snake_case__ : Optional[int] = image_mean snake_case__ : int = image_std snake_case__ : Dict = do_rescale snake_case__ : str = rescale_factor snake_case__ : Optional[int] = do_pad def __UpperCamelCase ( self ): 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 __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): if not batched: snake_case__ : str = image_inputs[0] if isinstance(__SCREAMING_SNAKE_CASE , Image.Image ): snake_case__ , snake_case__ : List[Any] = image.size else: snake_case__ , snake_case__ : Any = image.shape[1], image.shape[2] if w < h: snake_case__ : Tuple = int(self.size["""shortest_edge"""] * h / w ) snake_case__ : Optional[Any] = self.size["""shortest_edge"""] elif w > h: snake_case__ : str = self.size["""shortest_edge"""] snake_case__ : Optional[int] = int(self.size["""shortest_edge"""] * w / h ) else: snake_case__ : Tuple = self.size["""shortest_edge"""] snake_case__ : Union[str, Any] = self.size["""shortest_edge"""] else: snake_case__ : Dict = [] for image in image_inputs: snake_case__ , snake_case__ : Union[str, Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) snake_case__ : List[str] = max(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : item[0] )[0] snake_case__ : List[str] = max(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = DetaImageProcessor if is_vision_available() else None def __UpperCamelCase ( self ): snake_case__ : List[str] = DetaImageProcessingTester(self ) @property def __UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_std""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_rescale""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_pad""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """size""" ) ) def __UpperCamelCase ( self ): snake_case__ : Optional[int] = 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 , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input snake_case__ : Tuple = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values snake_case__ , snake_case__ : List[Any] = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__ , snake_case__ : List[str] = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = image_processing(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case__ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input snake_case__ : List[Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values snake_case__ , snake_case__ : int = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__ : Any = image_processing(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values snake_case__ , snake_case__ : Dict = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case__ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input snake_case__ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values snake_case__ , snake_case__ : Union[str, Any] = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__ : str = image_processing(__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).pixel_values snake_case__ , snake_case__ : str = self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE , batched=__SCREAMING_SNAKE_CASE ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __UpperCamelCase ( self ): # prepare image and target snake_case__ : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: snake_case__ : str = json.loads(f.read() ) snake_case__ : Any = {"""image_id""": 3_9_7_6_9, """annotations""": target} # encode them snake_case__ : Optional[Any] = DetaImageProcessor() snake_case__ : Optional[Any] = image_processing(images=__SCREAMING_SNAKE_CASE , annotations=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) # verify pixel values snake_case__ : List[Any] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["""pixel_values"""].shape , __SCREAMING_SNAKE_CASE ) snake_case__ : str = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area snake_case__ : Tuple = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , __SCREAMING_SNAKE_CASE ) ) # verify boxes snake_case__ : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , __SCREAMING_SNAKE_CASE ) snake_case__ : Any = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , __SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id snake_case__ : List[str] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , __SCREAMING_SNAKE_CASE ) ) # verify is_crowd snake_case__ : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , __SCREAMING_SNAKE_CASE ) ) # verify class_labels snake_case__ : Optional[int] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , __SCREAMING_SNAKE_CASE ) ) # verify orig_size snake_case__ : Tuple = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , __SCREAMING_SNAKE_CASE ) ) # verify size snake_case__ : Union[str, Any] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , __SCREAMING_SNAKE_CASE ) ) @slow def __UpperCamelCase ( self ): # prepare image, target and masks_path snake_case__ : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: snake_case__ : Optional[Any] = json.loads(f.read() ) snake_case__ : Dict = {"""file_name""": """000000039769.png""", """image_id""": 3_9_7_6_9, """segments_info""": target} snake_case__ : Optional[int] = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them snake_case__ : Union[str, Any] = DetaImageProcessor(format="""coco_panoptic""" ) snake_case__ : Optional[int] = image_processing(images=__SCREAMING_SNAKE_CASE , annotations=__SCREAMING_SNAKE_CASE , masks_path=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) # verify pixel values snake_case__ : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["""pixel_values"""].shape , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area snake_case__ : str = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , __SCREAMING_SNAKE_CASE ) ) # verify boxes snake_case__ : List[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , __SCREAMING_SNAKE_CASE ) snake_case__ : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , __SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id snake_case__ : Union[str, Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , __SCREAMING_SNAKE_CASE ) ) # verify is_crowd snake_case__ : int = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , __SCREAMING_SNAKE_CASE ) ) # verify class_labels snake_case__ : Union[str, Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , __SCREAMING_SNAKE_CASE ) ) # verify masks snake_case__ : Any = 8_2_2_8_7_3 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , __SCREAMING_SNAKE_CASE ) # verify orig_size snake_case__ : Dict = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , __SCREAMING_SNAKE_CASE ) ) # verify size snake_case__ : Optional[int] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , __SCREAMING_SNAKE_CASE ) )
38
'''simple docstring''' from __future__ import annotations A_ : str = "Muhammad Umer Farooq" A_ : Optional[Any] = "MIT" A_ : int = "1.0.0" A_ : int = "Muhammad Umer Farooq" A_ : int = "[email protected]" A_ : Dict = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): super().__init__() snake_case__ : list[str] = [] snake_case__ : List[Any] = domain def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: snake_case__ : str = parse.urljoin(self.domain , __SCREAMING_SNAKE_CASE ) self.urls.append(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return ".".join(get_sub_domain_name(__magic_name__ ).split(""".""" )[-2:] ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return parse.urlparse(__magic_name__ ).netloc def UpperCamelCase__ ( __magic_name__ : str = "https://github.com" ) -> list[str]: '''simple docstring''' snake_case__ : List[str] = get_domain_name(__magic_name__ ) # Initialize the parser snake_case__ : Optional[Any] = Parser(__magic_name__ ) try: # Open URL snake_case__ : Any = requests.get(__magic_name__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through snake_case__ : List[str] = set() for link in parser.urls: # open URL. # read = requests.get(link) try: snake_case__ : Tuple = requests.get(__magic_name__ ) # Get the valid email. snake_case__ : List[str] = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(__magic_name__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(__magic_name__ ) if __name__ == "__main__": A_ : str = emails_from_url("https://github.com") print(F'{len(emails)} emails found:') print("\n".join(sorted(emails)))
38
1
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : int ) -> int: '''simple docstring''' return int(input_a == input_a == 0 ) def UpperCamelCase__ ( ) -> None: '''simple docstring''' print("""Truth Table of NOR Gate:""" ) print("""| Input 1 | Input 2 | Output |""" ) print(f"| 0 | 0 | {nor_gate(0 , 0 )} |" ) print(f"| 0 | 1 | {nor_gate(0 , 1 )} |" ) print(f"| 1 | 0 | {nor_gate(1 , 0 )} |" ) print(f"| 1 | 1 | {nor_gate(1 , 1 )} |" ) if __name__ == "__main__": import doctest doctest.testmod() main()
38
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> Tuple: '''simple docstring''' if not head: return True # split the list to two parts snake_case__ , snake_case__ : Dict = head.next, head while fast and fast.next: snake_case__ : Any = fast.next.next snake_case__ : int = slow.next snake_case__ : Dict = slow.next snake_case__ : List[str] = None # Don't forget here! But forget still works! # reverse the second part snake_case__ : Tuple = None while second: snake_case__ : Tuple = second.next snake_case__ : Any = node snake_case__ : str = second snake_case__ : Optional[Any] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False snake_case__ : List[Any] = node.next snake_case__ : int = head.next return True def UpperCamelCase__ ( __magic_name__ : Any ) -> Optional[Any]: '''simple docstring''' if not head or not head.next: return True # 1. Get the midpoint (slow) snake_case__ : List[Any] = head while fast and fast.next: snake_case__ , snake_case__ : Any = fast.next.next, slow.next # 2. Push the second half into the stack snake_case__ : Tuple = [slow.val] while slow.next: snake_case__ : Optional[Any] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False snake_case__ : str = cur.next return True def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Tuple: '''simple docstring''' if not head or not head.next: return True snake_case__ : int = {} snake_case__ : Union[str, Any] = 0 while head: if head.val in d: d[head.val].append(__magic_name__ ) else: snake_case__ : Tuple = [pos] snake_case__ : Optional[Any] = head.next pos += 1 snake_case__ : int = pos - 1 snake_case__ : str = 0 for v in d.values(): if len(__magic_name__ ) % 2 != 0: middle += 1 else: snake_case__ : List[str] = 0 for i in range(0 , len(__magic_name__ ) ): if v[i] + v[len(__magic_name__ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
38
1
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : int = 10 ) -> str: '''simple docstring''' if not isinstance(__magic_name__ , __magic_name__ ) or n < 0: raise ValueError("""Invalid input""" ) snake_case__ : List[Any] = 10**n snake_case__ : Tuple = 2_84_33 * (pow(2 , 7_83_04_57 , __magic_name__ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F'{solution(10) = }')
38
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin A_ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ : str = 250004 A_ : str = 250020 @require_sentencepiece @require_tokenizers class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MBartTokenizer lowerCamelCase__ = MBartTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing snake_case__ : Tuple = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self ): snake_case__ : Tuple = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) snake_case__ : int = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) snake_case__ : Optional[int] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) snake_case__ : Optional[int] = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) snake_case__ : Union[str, Any] = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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 __UpperCamelCase ( self ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return snake_case__ : Optional[int] = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = tempfile.mkdtemp() snake_case__ : int = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) snake_case__ : List[str] = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way snake_case__ : Tuple = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True snake_case__ : Any = tempfile.mkdtemp() snake_case__ : Optional[int] = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) snake_case__ : int = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way snake_case__ : List[Any] = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False snake_case__ : Dict = tempfile.mkdtemp() snake_case__ : Union[str, Any] = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way snake_case__ : Dict = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = '''facebook/mbart-large-en-ro''' lowerCamelCase__ = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] lowerCamelCase__ = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] lowerCamelCase__ = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def __UpperCamelCase ( cls ): snake_case__ : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) snake_case__ : Any = 1 return cls def __UpperCamelCase ( self ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 2_5_0_0_2_0 ) def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) snake_case__ : List[str] = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] snake_case__ : List[Any] = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = ["""this is gunna be a long sentence """ * 2_0] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = 1_0 snake_case__ : int = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [2_5_0_0_2_6, 2_5_0_0_0_1] ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = tempfile.mkdtemp() snake_case__ : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = MBartTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) snake_case__ : int = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) snake_case__ : List[str] = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 1_4) , batch.input_ids.shape ) self.assertEqual((2, 1_4) , batch.attention_mask.shape ) snake_case__ : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) snake_case__ : Optional[int] = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=1_0 , return_tensors="""pt""" ) snake_case__ : str = targets["""input_ids"""] snake_case__ : Optional[Any] = shift_tokens_right(__SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[6_2, 3_0_3_4, 2, 2_5_0_0_0_4]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 2_5_0_0_0_1, } , )
38
1
'''simple docstring''' from math import sqrt def UpperCamelCase__ ( __magic_name__ : int ) -> int: '''simple docstring''' snake_case__ : Dict = 0 for i in range(1 , int(sqrt(__magic_name__ ) + 1 ) ): if n % i == 0 and i != sqrt(__magic_name__ ): total += i + n // i elif i == sqrt(__magic_name__ ): total += i return total - n def UpperCamelCase__ ( __magic_name__ : int = 1_00_00 ) -> int: '''simple docstring''' snake_case__ : Dict = sum( i for i in range(1 , __magic_name__ ) if sum_of_divisors(sum_of_divisors(__magic_name__ ) ) == i and sum_of_divisors(__magic_name__ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
38
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : int = logging.get_logger(__name__) A_ : Dict = { "google/bit-50": "https://huggingface.co/google/bit-50/resolve/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''bit''' lowerCamelCase__ = ['''preactivation''', '''bottleneck'''] lowerCamelCase__ = ['''SAME''', '''VALID'''] def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , __SCREAMING_SNAKE_CASE=[3, 4, 6, 3] , __SCREAMING_SNAKE_CASE="preactivation" , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) if global_padding is not None: if global_padding.upper() in self.supported_padding: snake_case__ : Tuple = global_padding.upper() else: raise ValueError(f"Padding strategy {global_padding} not supported" ) snake_case__ : List[str] = num_channels snake_case__ : Tuple = embedding_size snake_case__ : str = hidden_sizes snake_case__ : Optional[Any] = depths snake_case__ : List[Any] = layer_type snake_case__ : Dict = hidden_act snake_case__ : Union[str, Any] = global_padding snake_case__ : List[str] = num_groups snake_case__ : str = drop_path_rate snake_case__ : List[Any] = embedding_dynamic_padding snake_case__ : List[str] = output_stride snake_case__ : Dict = width_factor snake_case__ : List[str] = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] snake_case__ , snake_case__ : Dict = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
38
1
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to properly calculate the metrics on the # validation dataset when in a distributed system, and builds off the # `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## A_ : Optional[int] = 16 A_ : Optional[Any] = 32 def UpperCamelCase__ ( __magic_name__ : Accelerator , __magic_name__ : int = 16 ) -> int: '''simple docstring''' snake_case__ : List[Any] = AutoTokenizer.from_pretrained("""bert-base-cased""" ) snake_case__ : Optional[Any] = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__magic_name__ : List[Any] ): # max_length=None => use the model max length (it's actually the default) snake_case__ : Dict = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__magic_name__ , max_length=__magic_name__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): snake_case__ : Dict = datasets.map( __magic_name__ , batched=__magic_name__ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library snake_case__ : Union[str, Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__magic_name__ : str ): # On TPU it's best to pad everything to the same length or training will be very slow. snake_case__ : Union[str, Any] = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": snake_case__ : Dict = 16 elif accelerator.mixed_precision != "no": snake_case__ : Union[str, Any] = 8 else: snake_case__ : Optional[int] = None return tokenizer.pad( __magic_name__ , padding="""longest""" , max_length=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_tensors="""pt""" , ) # Instantiate dataloaders. snake_case__ : str = DataLoader( tokenized_datasets["""train"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) snake_case__ : str = DataLoader( tokenized_datasets["""validation"""] , shuffle=__magic_name__ , collate_fn=__magic_name__ , batch_size=__magic_name__ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": from accelerate.test_utils.training import mocked_dataloaders A_ : Tuple = mocked_dataloaders # noqa: F811 def UpperCamelCase__ ( __magic_name__ : Tuple , __magic_name__ : Any ) -> Union[str, Any]: '''simple docstring''' if os.environ.get("""TESTING_MOCKED_DATALOADERS""" , __magic_name__ ) == "1": snake_case__ : Optional[Any] = 2 # Initialize accelerator snake_case__ : Any = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs snake_case__ : Any = config["""lr"""] snake_case__ : List[str] = int(config["""num_epochs"""] ) snake_case__ : int = int(config["""seed"""] ) snake_case__ : Any = int(config["""batch_size"""] ) snake_case__ : Dict = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation snake_case__ : Optional[int] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: snake_case__ : Tuple = batch_size // MAX_GPU_BATCH_SIZE snake_case__ : Optional[Any] = MAX_GPU_BATCH_SIZE set_seed(__magic_name__ ) snake_case__ , snake_case__ : List[Any] = get_dataloaders(__magic_name__ , __magic_name__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) snake_case__ : str = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__magic_name__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). snake_case__ : List[Any] = model.to(accelerator.device ) # Instantiate optimizer snake_case__ : List[str] = AdamW(params=model.parameters() , lr=__magic_name__ ) # Instantiate scheduler snake_case__ : Optional[int] = get_linear_schedule_with_warmup( optimizer=__magic_name__ , num_warmup_steps=1_00 , num_training_steps=(len(__magic_name__ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : int = accelerator.prepare( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # Now we train the model for epoch in range(__magic_name__ ): model.train() for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) snake_case__ : Union[str, Any] = model(**__magic_name__ ) snake_case__ : str = outputs.loss snake_case__ : List[Any] = loss / gradient_accumulation_steps accelerator.backward(__magic_name__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() snake_case__ : Tuple = 0 for step, batch in enumerate(__magic_name__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): snake_case__ : Optional[int] = model(**__magic_name__ ) snake_case__ : Tuple = outputs.logits.argmax(dim=-1 ) snake_case__ , snake_case__ : int = accelerator.gather((predictions, batch["""labels"""]) ) # New Code # # First we check if it's a distributed system if accelerator.use_distributed: # Then see if we're on the last batch of our eval dataloader if step == len(__magic_name__ ) - 1: # Last batch needs to be truncated on distributed systems as it contains additional samples snake_case__ : Dict = predictions[: len(eval_dataloader.dataset ) - samples_seen] snake_case__ : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: # Otherwise we add the number of samples seen samples_seen += references.shape[0] # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: # accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=__magic_name__ , references=__magic_name__ , ) snake_case__ : Tuple = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , __magic_name__ ) def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : str = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__magic_name__ , default=__magic_name__ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) snake_case__ : Optional[Any] = parser.parse_args() snake_case__ : Any = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__magic_name__ , __magic_name__ ) if __name__ == "__main__": main()
38
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() A_ : Optional[int] = logging.get_logger(__name__) def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : str=False ) -> Tuple: '''simple docstring''' snake_case__ : int = [] # fmt: off # stem: rename_keys.append(("""cls_token""", """vit.embeddings.cls_token""") ) rename_keys.append(("""pos_embed""", """vit.embeddings.position_embeddings""") ) rename_keys.append(("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias""") ) # backbone rename_keys.append(("""patch_embed.backbone.stem.conv.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.bias""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias""") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias") ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case__ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) # fmt: on return rename_keys def UpperCamelCase__ ( __magic_name__ : Tuple , __magic_name__ : int , __magic_name__ : Tuple=False ) -> str: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: snake_case__ : int = """""" else: snake_case__ : Dict = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case__ : int = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) snake_case__ : Union[str, Any] = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] snake_case__ : Optional[Any] = in_proj_bias[: config.hidden_size] snake_case__ : List[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case__ : List[Any] = in_proj_weight[ -config.hidden_size :, : ] snake_case__ : Optional[int] = in_proj_bias[-config.hidden_size :] def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> List[str]: '''simple docstring''' snake_case__ : str = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(__magic_name__ , __magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : str ) -> Union[str, Any]: '''simple docstring''' snake_case__ : List[str] = dct.pop(__magic_name__ ) snake_case__ : Dict = val def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : Optional[int] = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) return im @torch.no_grad() def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : int=False ) -> Optional[int]: '''simple docstring''' snake_case__ : int = BitConfig( global_padding="""same""" , layer_type="""bottleneck""" , depths=(3, 4, 9) , out_features=["""stage3"""] , embedding_dynamic_padding=__magic_name__ , ) snake_case__ : Optional[int] = ViTHybridConfig(backbone_config=__magic_name__ , image_size=3_84 , num_labels=10_00 ) snake_case__ : Union[str, Any] = False # load original model from timm snake_case__ : List[Any] = timm.create_model(__magic_name__ , pretrained=__magic_name__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case__ : Optional[int] = timm_model.state_dict() if base_model: remove_classification_head_(__magic_name__ ) snake_case__ : int = create_rename_keys(__magic_name__ , __magic_name__ ) for src, dest in rename_keys: rename_key(__magic_name__ , __magic_name__ , __magic_name__ ) read_in_q_k_v(__magic_name__ , __magic_name__ , __magic_name__ ) snake_case__ : str = """huggingface/label-files""" snake_case__ : Union[str, Any] = """imagenet-1k-id2label.json""" snake_case__ : Dict = json.load(open(hf_hub_download(__magic_name__ , __magic_name__ , repo_type="""dataset""" ) , """r""" ) ) snake_case__ : List[Any] = {int(__magic_name__ ): v for k, v in idalabel.items()} snake_case__ : int = idalabel snake_case__ : str = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": snake_case__ : str = ViTHybridModel(__magic_name__ ).eval() else: snake_case__ : Union[str, Any] = ViTHybridForImageClassification(__magic_name__ ).eval() model.load_state_dict(__magic_name__ ) # create image processor snake_case__ : Optional[Any] = create_transform(**resolve_data_config({} , model=__magic_name__ ) ) snake_case__ : Union[str, Any] = transform.transforms snake_case__ : Tuple = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } snake_case__ : Any = ViTHybridImageProcessor( do_resize=__magic_name__ , size={"""shortest_edge""": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=__magic_name__ , crop_size={"""height""": timm_transforms[1].size[0], """width""": timm_transforms[1].size[1]} , do_normalize=__magic_name__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) snake_case__ : Any = prepare_img() snake_case__ : int = transform(__magic_name__ ).unsqueeze(0 ) snake_case__ : List[str] = processor(__magic_name__ , return_tensors="""pt""" ).pixel_values # verify pixel values assert torch.allclose(__magic_name__ , __magic_name__ ) # verify logits with torch.no_grad(): snake_case__ : Optional[Any] = model(__magic_name__ ) snake_case__ : Union[str, Any] = outputs.logits print("""Predicted class:""" , logits.argmax(-1 ).item() ) if base_model: snake_case__ : Dict = timm_model.forward_features(__magic_name__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(__magic_name__ , outputs.pooler_output , atol=1E-3 ) else: snake_case__ : int = timm_model(__magic_name__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__magic_name__ , outputs.logits , atol=1E-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(__magic_name__ ) if push_to_hub: print(f"Pushing model and processor to the hub {vit_name}" ) model.push_to_hub(f"ybelkada/{vit_name}" ) processor.push_to_hub(f"ybelkada/{vit_name}" ) if __name__ == "__main__": A_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) A_ : Union[str, Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
38
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_donut import DonutImageProcessor A_ : Union[str, Any] = logging.get_logger(__name__) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): warnings.warn( """The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DonutImageProcessor instead.""" , __SCREAMING_SNAKE_CASE , ) super().__init__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
38
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = 42 class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("DownEncoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE=True , ): super().__init__() snake_case__ : str = layers_per_block snake_case__ : int = torch.nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : List[Any] = None snake_case__ : List[Any] = nn.ModuleList([] ) # down snake_case__ : Union[str, Any] = block_out_channels[0] for i, down_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = output_channel snake_case__ : Union[str, Any] = block_out_channels[i] snake_case__ : int = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : str = get_down_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) self.down_blocks.append(__SCREAMING_SNAKE_CASE ) # mid snake_case__ : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # out snake_case__ : Tuple = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : str = 2 * out_channels if double_z else out_channels snake_case__ : int = nn.Convad(block_out_channels[-1] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : Union[str, Any] = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = x snake_case__ : int = self.conv_in(__SCREAMING_SNAKE_CASE ) if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) # middle snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: for down_block in self.down_blocks: snake_case__ : Dict = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE ) else: # down for down_block in self.down_blocks: snake_case__ : List[str] = down_block(__SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = self.mid_block(__SCREAMING_SNAKE_CASE ) # post-process snake_case__ : Any = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : str = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("UpDecoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE="group" , ): super().__init__() snake_case__ : Any = layers_per_block snake_case__ : Optional[Any] = nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : Union[str, Any] = None snake_case__ : Dict = nn.ModuleList([] ) snake_case__ : Optional[int] = in_channels if norm_type == """spatial""" else None # mid snake_case__ : Tuple = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # up snake_case__ : List[Any] = list(reversed(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[Any] = reversed_block_out_channels[0] for i, up_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = output_channel snake_case__ : Optional[Any] = reversed_block_out_channels[i] snake_case__ : List[str] = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : int = get_up_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block + 1 , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , prev_output_channel=__SCREAMING_SNAKE_CASE , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , resnet_time_scale_shift=__SCREAMING_SNAKE_CASE , ) self.up_blocks.append(__SCREAMING_SNAKE_CASE ) snake_case__ : int = output_channel # out if norm_type == "spatial": snake_case__ : List[Any] = SpatialNorm(block_out_channels[0] , __SCREAMING_SNAKE_CASE ) else: snake_case__ : Any = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : Union[str, Any] = nn.Convad(block_out_channels[0] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : int = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): snake_case__ : Union[str, Any] = z snake_case__ : Any = self.conv_in(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle snake_case__ : int = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) snake_case__ : int = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : List[str] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : Dict = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : List[Any] = self.mid_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : Dict = up_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # post-process if latent_embeds is None: snake_case__ : Optional[Any] = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) else: snake_case__ : str = self.conv_norm_out(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="random" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True ): super().__init__() snake_case__ : int = n_e snake_case__ : Optional[int] = vq_embed_dim snake_case__ : int = beta snake_case__ : Optional[int] = legacy snake_case__ : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) snake_case__ : List[str] = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) snake_case__ : Optional[Any] = self.used.shape[0] snake_case__ : List[str] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": snake_case__ : Dict = self.re_embed snake_case__ : List[str] = self.re_embed + 1 print( f"Remapping {self.n_e} indices to {self.re_embed} indices. " f"Using {self.unknown_index} for unknown indices." ) else: snake_case__ : Union[str, Any] = n_e snake_case__ : str = sane_index_shape def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : Dict = inds.reshape(ishape[0] , -1 ) snake_case__ : Any = self.used.to(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = (inds[:, :, None] == used[None, None, ...]).long() snake_case__ : List[Any] = match.argmax(-1 ) snake_case__ : List[str] = match.sum(2 ) < 1 if self.unknown_index == "random": snake_case__ : List[str] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: snake_case__ : Optional[Any] = self.unknown_index return new.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : int = inds.reshape(ishape[0] , -1 ) snake_case__ : Optional[int] = self.used.to(__SCREAMING_SNAKE_CASE ) if self.re_embed > self.used.shape[0]: # extra token snake_case__ : List[Any] = 0 # simply set to zero snake_case__ : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __SCREAMING_SNAKE_CASE ) return back.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): # reshape z -> (batch, height, width, channel) and flatten snake_case__ : Any = z.permute(0 , 2 , 3 , 1 ).contiguous() snake_case__ : Optional[Any] = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z snake_case__ : Dict = torch.argmin(torch.cdist(__SCREAMING_SNAKE_CASE , self.embedding.weight ) , dim=1 ) snake_case__ : Union[str, Any] = self.embedding(__SCREAMING_SNAKE_CASE ).view(z.shape ) snake_case__ : List[str] = None snake_case__ : Union[str, Any] = None # compute loss for embedding if not self.legacy: snake_case__ : Tuple = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: snake_case__ : List[Any] = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients snake_case__ : Any = z + (z_q - z).detach() # reshape back to match original input shape snake_case__ : Union[str, Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: snake_case__ : List[Any] = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis snake_case__ : str = self.remap_to_used(__SCREAMING_SNAKE_CASE ) snake_case__ : str = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: snake_case__ : Tuple = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # shape specifying (batch, height, width, channel) if self.remap is not None: snake_case__ : List[Any] = indices.reshape(shape[0] , -1 ) # add batch axis snake_case__ : Optional[int] = self.unmap_to_all(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = indices.reshape(-1 ) # flatten again # get quantized latent vectors snake_case__ : int = self.embedding(__SCREAMING_SNAKE_CASE ) if shape is not None: snake_case__ : str = z_q.view(__SCREAMING_SNAKE_CASE ) # reshape back to match original input shape snake_case__ : str = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): snake_case__ : Tuple = parameters snake_case__ , snake_case__ : Any = torch.chunk(__SCREAMING_SNAKE_CASE , 2 , dim=1 ) snake_case__ : Union[str, Any] = torch.clamp(self.logvar , -30.0 , 20.0 ) snake_case__ : Optional[int] = deterministic snake_case__ : Optional[int] = torch.exp(0.5 * self.logvar ) snake_case__ : Any = torch.exp(self.logvar ) if self.deterministic: snake_case__ : List[str] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE = None ): # make sure sample is on the same device as the parameters and has same dtype snake_case__ : Dict = randn_tensor( self.mean.shape , generator=__SCREAMING_SNAKE_CASE , device=self.parameters.device , dtype=self.parameters.dtype ) snake_case__ : Optional[int] = self.mean + self.std * sample return x def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) snake_case__ : Any = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): return self.mean
38
1
'''simple docstring''' import random def UpperCamelCase__ ( __magic_name__ : int ) -> bool: '''simple docstring''' snake_case__ : List[str] = num - 1 snake_case__ : List[Any] = 0 while s % 2 == 0: snake_case__ : Optional[Any] = s // 2 t += 1 for _ in range(5 ): snake_case__ : Any = random.randrange(2 , num - 1 ) snake_case__ : Optional[Any] = pow(__magic_name__ , __magic_name__ , __magic_name__ ) if v != 1: snake_case__ : int = 0 while v != (num - 1): if i == t - 1: return False else: snake_case__ : int = i + 1 snake_case__ : str = (v**2) % num return True def UpperCamelCase__ ( __magic_name__ : int ) -> bool: '''simple docstring''' if num < 2: return False snake_case__ : Dict = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : int = 10_24 ) -> int: '''simple docstring''' while True: snake_case__ : Optional[Any] = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(__magic_name__ ): return num if __name__ == "__main__": A_ : Dict = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
38
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1_6 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=[0, 1, 2, 3] , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_7 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=[1, 3_8_4, 2_4, 2_4] , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , ): snake_case__ : str = parent snake_case__ : Union[str, Any] = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : Optional[int] = patch_size snake_case__ : List[str] = num_channels snake_case__ : Any = is_training snake_case__ : int = use_labels snake_case__ : str = hidden_size snake_case__ : Tuple = num_hidden_layers snake_case__ : str = backbone_out_indices snake_case__ : List[Any] = num_attention_heads snake_case__ : Dict = intermediate_size snake_case__ : Optional[Any] = hidden_act snake_case__ : str = hidden_dropout_prob snake_case__ : int = attention_probs_dropout_prob snake_case__ : Dict = initializer_range snake_case__ : Optional[int] = num_labels snake_case__ : str = backbone_featmap_shape snake_case__ : List[Any] = scope snake_case__ : Optional[Any] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) snake_case__ : List[Any] = (image_size // patch_size) ** 2 snake_case__ : Union[str, Any] = num_patches + 1 def __UpperCamelCase ( self ): snake_case__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : str = None if self.use_labels: snake_case__ : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): snake_case__ : Any = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [9_6, 1_9_2, 3_8_4, 7_6_8], """num_groups""": 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , 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=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=__SCREAMING_SNAKE_CASE , backbone_featmap_shape=self.backbone_featmap_shape , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = DPTModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Union[str, Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = self.num_labels snake_case__ : str = DPTForDepthEstimation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Optional[Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = self.num_labels snake_case__ : Dict = DPTForSemanticSegmentation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : str = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () lowerCamelCase__ = ( { '''depth-estimation''': DPTForDepthEstimation, '''feature-extraction''': DPTModel, '''image-segmentation''': DPTForSemanticSegmentation, } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : List[Any] = DPTModelTester(self ) snake_case__ : Any = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""DPT does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Tuple = model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : str = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : List[str] = [*signature.parameters.keys()] snake_case__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : int = True if model_class in get_values(__SCREAMING_SNAKE_CASE ): continue snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.train() snake_case__ : Optional[Any] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCamelCase ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Union[str, Any] = False snake_case__ : str = True if model_class in get_values(__SCREAMING_SNAKE_CASE ) or not model_class.supports_gradient_checkpointing: continue snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.train() snake_case__ : List[str] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCamelCase ( self ): snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : str = _config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: snake_case__ : Any = model_class(config=__SCREAMING_SNAKE_CASE ) # Skip the check for the backbone snake_case__ : str = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": snake_case__ : Optional[int] = [f"{name}.{key}" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCamelCase ( self ): pass @slow def __UpperCamelCase ( self ): for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: snake_case__ : List[str] = DPTModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Dict = """add""" with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = DPTForDepthEstimation(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( ) -> Dict: '''simple docstring''' snake_case__ : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision @slow class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Dict = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" ) snake_case__ : Union[str, Any] = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = prepare_img() snake_case__ : Optional[int] = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): snake_case__ : Dict = model(**__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = outputs.predicted_depth # verify the predicted depth snake_case__ : Any = torch.Size((1, 3_8_4, 3_8_4) ) self.assertEqual(predicted_depth.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0 , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
1
'''simple docstring''' import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_3 , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=9_9 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_7 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=1_6 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=None , ): snake_case__ : List[str] = parent snake_case__ : Tuple = batch_size snake_case__ : str = seq_length snake_case__ : Optional[Any] = is_training snake_case__ : str = use_input_mask snake_case__ : List[str] = use_token_type_ids snake_case__ : Optional[Any] = use_labels snake_case__ : Any = vocab_size snake_case__ : List[Any] = hidden_size snake_case__ : List[Any] = num_hidden_layers snake_case__ : Optional[int] = num_attention_heads snake_case__ : Tuple = intermediate_size snake_case__ : Dict = hidden_act snake_case__ : Optional[Any] = hidden_dropout_prob snake_case__ : int = attention_probs_dropout_prob snake_case__ : Tuple = max_position_embeddings snake_case__ : Union[str, Any] = type_vocab_size snake_case__ : List[str] = type_sequence_label_size snake_case__ : Any = initializer_range snake_case__ : str = num_labels snake_case__ : Optional[int] = num_choices snake_case__ : int = scope snake_case__ : Tuple = vocab_size - 1 def __UpperCamelCase ( self ): snake_case__ : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case__ : str = None if self.use_input_mask: snake_case__ : str = random_attention_mask([self.batch_size, self.seq_length] ) snake_case__ : Any = None if self.use_labels: snake_case__ : int = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case__ : List[str] = self.get_config() return config, input_ids, input_mask, token_labels def __UpperCamelCase ( self ): return GPTNeoXConfig( 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=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = self.prepare_config_and_inputs() snake_case__ : Dict = True return config, input_ids, input_mask, token_labels def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = GPTNeoXModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Dict = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ) snake_case__ : str = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = True snake_case__ : Tuple = GPTNeoXModel(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : List[Any] = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = GPTNeoXForCausalLM(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : List[str] = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = self.num_labels snake_case__ : Any = GPTNeoXForQuestionAnswering(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Dict = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = self.num_labels snake_case__ : str = GPTNeoXForSequenceClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case__ : str = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[int] = self.num_labels snake_case__ : Union[str, Any] = GPTNeoXForTokenClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : List[str] = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = True snake_case__ : List[str] = GPTNeoXForCausalLM(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() # first forward pass snake_case__ : Dict = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids snake_case__ : List[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) snake_case__ : Dict = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and snake_case__ : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case__ : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) snake_case__ : Optional[Any] = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , output_hidden_states=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = output_from_no_past["""hidden_states"""][0] snake_case__ : Union[str, Any] = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , past_key_values=__SCREAMING_SNAKE_CASE , output_hidden_states=__SCREAMING_SNAKE_CASE , )["""hidden_states"""][0] # select random slice snake_case__ : str = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case__ : str = output_from_no_past[:, -3:, random_slice_idx].detach() snake_case__ : Dict = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __UpperCamelCase ( self ): snake_case__ : str = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Any = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) lowerCamelCase__ = (GPTNeoXForCausalLM,) if is_torch_available() else () lowerCamelCase__ = ( { '''feature-extraction''': GPTNeoXModel, '''question-answering''': GPTNeoXForQuestionAnswering, '''text-classification''': GPTNeoXForSequenceClassification, '''text-generation''': GPTNeoXForCausalLM, '''token-classification''': GPTNeoXForTokenClassification, '''zero-shot''': GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : Dict = GPTNeoXModelTester(self ) snake_case__ : Optional[int] = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=6_4 , num_attention_heads=8 ) def __UpperCamelCase ( self ): self.config_tester.run_common_tests() def __UpperCamelCase ( self ): snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # This regression test was failing with PyTorch < 1.3 snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_decoder() snake_case__ : Any = None self.model_tester.create_and_check_model_as_decoder(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ , snake_case__ , snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__SCREAMING_SNAKE_CASE ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def __UpperCamelCase ( self ): pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ , snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Union[str, Any] = ids_tensor([1, 1_0] , config.vocab_size ) snake_case__ : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights snake_case__ : Dict = GPTNeoXModel(__SCREAMING_SNAKE_CASE ) original_model.to(__SCREAMING_SNAKE_CASE ) original_model.eval() snake_case__ : int = original_model(__SCREAMING_SNAKE_CASE ).last_hidden_state snake_case__ : str = original_model(__SCREAMING_SNAKE_CASE ).last_hidden_state set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights snake_case__ : Dict = {"""type""": scaling_type, """factor""": 10.0} snake_case__ : Optional[Any] = GPTNeoXModel(__SCREAMING_SNAKE_CASE ) scaled_model.to(__SCREAMING_SNAKE_CASE ) scaled_model.eval() snake_case__ : Any = scaled_model(__SCREAMING_SNAKE_CASE ).last_hidden_state snake_case__ : Optional[int] = scaled_model(__SCREAMING_SNAKE_CASE ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1e-5 ) ) @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self ): snake_case__ : Any = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: snake_case__ : Tuple = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer("""My favorite food is""" , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 snake_case__ : str = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" snake_case__ : Union[str, Any] = model.generate(**__SCREAMING_SNAKE_CASE , do_sample=__SCREAMING_SNAKE_CASE , max_new_tokens=2_0 ) snake_case__ : Optional[int] = tokenizer.batch_decode(__SCREAMING_SNAKE_CASE )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
38
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Dict: '''simple docstring''' snake_case__ : int = botoa.client("""iam""" ) snake_case__ : Union[str, Any] = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=__magic_name__ , AssumeRolePolicyDocument=json.dumps(__magic_name__ , indent=2 ) ) snake_case__ : Dict = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=__magic_name__ , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(__magic_name__ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def UpperCamelCase__ ( __magic_name__ : Any ) -> Tuple: '''simple docstring''' snake_case__ : List[str] = botoa.client("""iam""" ) return iam_client.get_role(RoleName=__magic_name__ )["Role"]["Arn"] def UpperCamelCase__ ( ) -> Tuple: '''simple docstring''' snake_case__ : Union[str, Any] = _ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , __magic_name__ , ) snake_case__ : List[Any] = None if credentials_configuration == 0: snake_case__ : Dict = _ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) snake_case__ : List[str] = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) snake_case__ : List[str] = _ask_field("""AWS Access Key ID: """ ) snake_case__ : int = aws_access_key_id snake_case__ : Optional[Any] = _ask_field("""AWS Secret Access Key: """ ) snake_case__ : List[str] = aws_secret_access_key snake_case__ : Tuple = _ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) snake_case__ : Optional[int] = aws_region snake_case__ : int = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , __magic_name__ , ) if role_management == 0: snake_case__ : Optional[Any] = _ask_field("""Enter your IAM role name: """ ) else: snake_case__ : Optional[int] = """accelerate_sagemaker_execution_role""" print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(__magic_name__ ) snake_case__ : Dict = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Any = None if is_custom_docker_image: snake_case__ : str = _ask_field("""Enter your Docker image: """ , lambda __magic_name__ : str(__magic_name__ ).lower() ) snake_case__ : Tuple = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : List[Any] = None if is_sagemaker_inputs_enabled: snake_case__ : str = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Optional[int] = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Optional[Any] = None if is_sagemaker_metrics_enabled: snake_case__ : List[Any] = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Tuple = _ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) snake_case__ : Any = {} snake_case__ : List[Any] = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_dynamo: snake_case__ : str = """dynamo_""" snake_case__ : Tuple = _ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) snake_case__ : List[str] = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_custom_options: snake_case__ : str = _ask_options( """Which mode do you want to use?""" , __magic_name__ , lambda __magic_name__ : TORCH_DYNAMO_MODES[int(__magic_name__ )] , default="""default""" , ) snake_case__ : Union[str, Any] = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : str = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Dict = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: snake_case__ : List[str] = _ask_options( __magic_name__ , __magic_name__ , lambda __magic_name__ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(__magic_name__ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" snake_case__ : Optional[int] = _ask_field(__magic_name__ , lambda __magic_name__ : str(__magic_name__ ).lower() , default="""ml.p3.2xlarge""" ) snake_case__ : Dict = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): snake_case__ : Optional[Any] = _ask_field( """How many machines do you want use? [1]: """ , __magic_name__ , default=1 , ) snake_case__ : Union[str, Any] = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=__magic_name__ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=__magic_name__ , use_cpu=__magic_name__ , dynamo_config=__magic_name__ , eca_instance_type=__magic_name__ , profile=__magic_name__ , region=__magic_name__ , iam_role_name=__magic_name__ , mixed_precision=__magic_name__ , num_machines=__magic_name__ , sagemaker_inputs_file=__magic_name__ , sagemaker_metrics_file=__magic_name__ , )
38
1
'''simple docstring''' import json import os import tempfile from unittest.mock import patch import torch from torch.utils.data import DataLoader, TensorDataset from accelerate import DistributedType, infer_auto_device_map, init_empty_weights from accelerate.accelerator import Accelerator from accelerate.state import GradientState, PartialState from accelerate.test_utils import require_bnb, require_multi_gpu, slow from accelerate.test_utils.testing import AccelerateTestCase, require_cuda from accelerate.utils import patch_environment def UpperCamelCase__ ( ) -> Any: '''simple docstring''' snake_case__ : Any = torch.nn.Linear(2 , 4 ) snake_case__ : Union[str, Any] = torch.optim.AdamW(model.parameters() , lr=1.0 ) snake_case__ : Union[str, Any] = torch.optim.lr_scheduler.OneCycleLR(__magic_name__ , max_lr=0.01 , steps_per_epoch=2 , epochs=1 ) snake_case__ : str = DataLoader(TensorDataset(torch.tensor([1, 2, 3] ) ) ) snake_case__ : Any = DataLoader(TensorDataset(torch.tensor([4, 5, 6] ) ) ) return model, optimizer, scheduler, train_dl, valid_dl def UpperCamelCase__ ( __magic_name__ : str ) -> Dict: '''simple docstring''' return (model.weight.abs().sum() + model.bias.abs().sum()).item() def UpperCamelCase__ ( __magic_name__ : List[str] ) -> List[Any]: '''simple docstring''' snake_case__ : int = torch.nn.Linear(*tuple(model.weight.T.shape ) ).state_dict() model.load_state_dict(__magic_name__ ) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @require_cuda def __UpperCamelCase ( self ): snake_case__ : Any = Accelerator() assert PartialState._shared_state["_cpu"] is False assert PartialState._shared_state["device"].type == "cuda" with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case__ : int = Accelerator(cpu=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = Accelerator() snake_case__ : Optional[int] = GradientState() assert state.num_steps == 1 snake_case__ : Optional[int] = 4 assert state.num_steps == 4 assert state.sync_gradients is True snake_case__ : int = False assert state.sync_gradients is False GradientState._reset_state() def __UpperCamelCase ( self ): snake_case__ : Any = Accelerator() snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : int = create_components() ( ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ) : str = accelerator.prepare(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(prepared_model in accelerator._models ) self.assertTrue(prepared_optimizer in accelerator._optimizers ) self.assertTrue(prepared_scheduler in accelerator._schedulers ) self.assertTrue(prepared_train_dl in accelerator._dataloaders ) self.assertTrue(prepared_valid_dl in accelerator._dataloaders ) def __UpperCamelCase ( self ): snake_case__ : str = Accelerator() snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Optional[int] = create_components() accelerator.prepare(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) accelerator.free_memory() self.assertTrue(len(accelerator._models ) == 0 ) self.assertTrue(len(accelerator._optimizers ) == 0 ) self.assertTrue(len(accelerator._schedulers ) == 0 ) self.assertTrue(len(accelerator._dataloaders ) == 0 ) def __UpperCamelCase ( self ): PartialState._reset_state() # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist def noop(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): pass with patch("""torch.cuda.set_device""" , __SCREAMING_SNAKE_CASE ), patch_environment(ACCELERATE_TORCH_DEVICE="""cuda:64""" ): snake_case__ : Optional[int] = Accelerator() self.assertEqual(str(accelerator.state.device ) , """cuda:64""" ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = Accelerator() snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = create_components() accelerator.prepare(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = get_signature(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(__SCREAMING_SNAKE_CASE ) # make sure random weights don't match load_random_weights(__SCREAMING_SNAKE_CASE ) self.assertTrue(abs(model_signature - get_signature(__SCREAMING_SNAKE_CASE ) ) > 1e-3 ) # make sure loaded weights match accelerator.load_state(__SCREAMING_SNAKE_CASE ) self.assertTrue(abs(model_signature - get_signature(__SCREAMING_SNAKE_CASE ) ) < 1e-3 ) def __UpperCamelCase ( self ): snake_case__ : Dict = Accelerator() snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Optional[int] = create_components() accelerator.prepare(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = get_signature(__SCREAMING_SNAKE_CASE ) # saving hook def save_config(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = {"""class_name""": models[0].__class__.__name__} with open(os.path.join(__SCREAMING_SNAKE_CASE , """data.json""" ) , """w""" ) as f: json.dump(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # loading hook def load_config(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): with open(os.path.join(__SCREAMING_SNAKE_CASE , """data.json""" ) , """r""" ) as f: snake_case__ : Tuple = json.load(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = config["""class_name"""] snake_case__ : Any = accelerator.register_save_state_pre_hook(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = accelerator.register_load_state_pre_hook(__SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(__SCREAMING_SNAKE_CASE ) # make sure random weights don't match with hooks load_random_weights(__SCREAMING_SNAKE_CASE ) self.assertTrue(abs(model_signature - get_signature(__SCREAMING_SNAKE_CASE ) ) > 1e-3 ) # random class name to verify correct one is loaded snake_case__ : Optional[Any] = """random""" # make sure loaded weights match with hooks accelerator.load_state(__SCREAMING_SNAKE_CASE ) self.assertTrue(abs(model_signature - get_signature(__SCREAMING_SNAKE_CASE ) ) < 1e-3 ) # mode.class_name is loaded from config self.assertTrue(model.class_name == model.__class__.__name__ ) # remove hooks save_hook.remove() load_hook.remove() with tempfile.TemporaryDirectory() as tmpdirname: accelerator.save_state(__SCREAMING_SNAKE_CASE ) # make sure random weights don't match with hooks removed load_random_weights(__SCREAMING_SNAKE_CASE ) self.assertTrue(abs(model_signature - get_signature(__SCREAMING_SNAKE_CASE ) ) > 1e-3 ) # random class name to verify correct one is loaded snake_case__ : Dict = """random""" # make sure loaded weights match with hooks removed accelerator.load_state(__SCREAMING_SNAKE_CASE ) self.assertTrue(abs(model_signature - get_signature(__SCREAMING_SNAKE_CASE ) ) < 1e-3 ) # mode.class_name is NOT loaded from config self.assertTrue(model.class_name != model.__class__.__name__ ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = Accelerator() snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Optional[int] = create_components() snake_case__ : Dict = None # This should work snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = accelerator.prepare( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertTrue(dummy_obj is None ) def __UpperCamelCase ( self ): snake_case__ : Dict = Accelerator() snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Tuple = create_components() snake_case__ : int = [1, 2, 3] # This should work snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ : Optional[int] = accelerator.prepare( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual( getattr(__SCREAMING_SNAKE_CASE , """_is_accelerate_prepared""" , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """Dummy object should have `_is_accelerate_prepared` set to `True`""" , ) self.assertEqual( getattr(__SCREAMING_SNAKE_CASE , """_is_accelerate_prepared""" , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """Model is missing `_is_accelerator_prepared` or is set to `False`""" , ) self.assertEqual( getattr(__SCREAMING_SNAKE_CASE , """_is_accelerate_prepared""" , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """Optimizer is missing `_is_accelerator_prepared` or is set to `False`""" , ) self.assertEqual( getattr(__SCREAMING_SNAKE_CASE , """_is_accelerate_prepared""" , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """Scheduler is missing `_is_accelerator_prepared` or is set to `False`""" , ) self.assertEqual( getattr(__SCREAMING_SNAKE_CASE , """_is_accelerate_prepared""" , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`""" , ) self.assertEqual( getattr(__SCREAMING_SNAKE_CASE , """_is_accelerate_prepared""" , __SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`""" , ) @slow @require_bnb def __UpperCamelCase ( self ): from transformers import AutoModelForCausalLM snake_case__ : List[Any] = AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , load_in_abit=__SCREAMING_SNAKE_CASE , device_map={"""""": 0} , ) snake_case__ : str = Accelerator() # This should work snake_case__ : List[Any] = accelerator.prepare(__SCREAMING_SNAKE_CASE ) @slow @require_bnb def __UpperCamelCase ( self ): from transformers import AutoModelForCausalLM snake_case__ : List[str] = Accelerator() with init_empty_weights(): snake_case__ : Any = AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , ) model.tie_weights() snake_case__ : Optional[int] = infer_auto_device_map(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = """cpu""" snake_case__ : Optional[int] = AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , device_map=__SCREAMING_SNAKE_CASE , load_in_abit=__SCREAMING_SNAKE_CASE , llm_inta_enable_fpaa_cpu_offload=__SCREAMING_SNAKE_CASE ) # This should not work and get value error with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case__ : str = accelerator.prepare(__SCREAMING_SNAKE_CASE ) @slow @require_bnb @require_multi_gpu def __UpperCamelCase ( self ): from transformers import AutoModelForCausalLM snake_case__ : Any = {"""distributed_type""": DistributedType.MULTI_GPU} with init_empty_weights(): snake_case__ : List[str] = AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , ) model.tie_weights() snake_case__ : Tuple = infer_auto_device_map(__SCREAMING_SNAKE_CASE ) snake_case__ : str = 1 snake_case__ : Any = AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , load_in_abit=__SCREAMING_SNAKE_CASE , device_map=__SCREAMING_SNAKE_CASE , ) snake_case__ : List[str] = Accelerator() # This should not work and get value error with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case__ : Union[str, Any] = accelerator.prepare(__SCREAMING_SNAKE_CASE ) PartialState._reset_state() @slow @require_bnb @require_multi_gpu def __UpperCamelCase ( self ): from transformers import AutoModelForCausalLM with init_empty_weights(): snake_case__ : Tuple = AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , ) snake_case__ : Optional[Any] = infer_auto_device_map(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = 1 snake_case__ : List[str] = AutoModelForCausalLM.from_pretrained( """EleutherAI/gpt-neo-125m""" , load_in_abit=__SCREAMING_SNAKE_CASE , device_map=__SCREAMING_SNAKE_CASE , ) snake_case__ : Tuple = Accelerator() # This should work snake_case__ : Any = accelerator.prepare(__SCREAMING_SNAKE_CASE ) @require_cuda def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = torch.nn.Linear(1_0 , 1_0 ) snake_case__ : Tuple = torch.optim.SGD(model.parameters() , lr=0.01 ) snake_case__ : Union[str, Any] = Accelerator(cpu=__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = accelerator.prepare(__SCREAMING_SNAKE_CASE )
38
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def UpperCamelCase__ ( __magic_name__ : str = "laptop" ) -> DataFrame: '''simple docstring''' snake_case__ : Union[str, Any] = f"https://www.amazon.in/laptop/s?k={product}" snake_case__ : List[str] = { """User-Agent""": """Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36""", """Accept-Language""": """en-US, en;q=0.5""", } snake_case__ : int = BeautifulSoup(requests.get(__magic_name__ , headers=__magic_name__ ).text ) # Initialize a Pandas dataframe with the column titles snake_case__ : Optional[Any] = DataFrame( columns=[ """Product Title""", """Product Link""", """Current Price of the product""", """Product Rating""", """MRP of the product""", """Discount""", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( """div""" , attrs={"""class""": """s-result-item""", """data-component-type""": """s-search-result"""} , ) , soup.find_all("""div""" , attrs={"""class""": """a-row a-size-base a-color-base"""} ) , ): try: snake_case__ : Optional[int] = item.ha.text snake_case__ : Any = """https://www.amazon.in/""" + item.ha.a["""href"""] snake_case__ : List[str] = item.find("""span""" , attrs={"""class""": """a-offscreen"""} ).text try: snake_case__ : Dict = item.find("""span""" , attrs={"""class""": """a-icon-alt"""} ).text except AttributeError: snake_case__ : Optional[int] = """Not available""" try: snake_case__ : Tuple = ( """₹""" + item.find( """span""" , attrs={"""class""": """a-price a-text-price"""} ).text.split("""₹""" )[1] ) except AttributeError: snake_case__ : Optional[Any] = """""" try: snake_case__ : str = float( ( ( float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) - float(product_price.strip("""₹""" ).replace(""",""" , """""" ) ) ) / float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) ) * 1_00 ) except ValueError: snake_case__ : List[Any] = float("""nan""" ) except AttributeError: pass snake_case__ : str = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] snake_case__ : List[Any] = """ """ snake_case__ : Union[str, Any] = """ """ data_frame.index += 1 return data_frame if __name__ == "__main__": A_ : int = "headphones" get_amazon_product_data(product).to_csv(F'Amazon Product Data for {product}.csv')
38
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : Optional[Any] = { "configuration_xmod": [ "XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP", "XmodConfig", "XmodOnnxConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = [ "XMOD_PRETRAINED_MODEL_ARCHIVE_LIST", "XmodForCausalLM", "XmodForMaskedLM", "XmodForMultipleChoice", "XmodForQuestionAnswering", "XmodForSequenceClassification", "XmodForTokenClassification", "XmodModel", "XmodPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys A_ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
38
'''simple docstring''' import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = LongformerTokenizer lowerCamelCase__ = True lowerCamelCase__ = LongformerTokenizerFast lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case__ : Union[str, Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] snake_case__ : Optional[int] = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) snake_case__ : int = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] snake_case__ : Any = {"""unk_token""": """<unk>"""} snake_case__ : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) snake_case__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : str = """lower newer""" snake_case__ : Dict = """lower newer""" return input_text, output_text def __UpperCamelCase ( self ): snake_case__ : int = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case__ : Tuple = """lower newer""" snake_case__ : Optional[Any] = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] snake_case__ : Tuple = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) # , add_prefix_space=True) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokens + [tokenizer.unk_token] snake_case__ : List[Any] = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Tuple = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [0, 3_1_4_1_4, 2_3_2, 3_2_8, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [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] , ) @slow def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.tokenizer_class.from_pretrained("""allenai/longformer-base-4096""" ) snake_case__ : int = tokenizer.encode("""sequence builders""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer.encode( """sequence builders""" , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.get_tokenizer() snake_case__ : int = """Encode this sequence.""" snake_case__ : Union[str, Any] = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments snake_case__ : Optional[int] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) snake_case__ : List[str] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Testing spaces after special tokens snake_case__ : List[str] = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE )} ) # mask token has a left space snake_case__ : Dict = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) snake_case__ : str = """Encode <mask> sequence""" snake_case__ : Tuple = """Encode <mask>sequence""" snake_case__ : Union[str, Any] = tokenizer.encode(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = encoded.index(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer.encode(__SCREAMING_SNAKE_CASE ) snake_case__ : str = encoded.index(__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = """A, <mask> AllenNLP sentence.""" snake_case__ : str = tokenizer_r.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer_p.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) snake_case__ : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) snake_case__ : Dict = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def __UpperCamelCase ( self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): snake_case__ : Any = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) snake_case__ : List[str] = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state["""add_prefix_space"""] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state["""trim_offsets"""] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : Union[str, Any] = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` snake_case__ : Any = f"{text_of_1_token} {text_of_1_token}" snake_case__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Tuple = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Optional[Any] = f" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) snake_case__ : Dict = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ) + 1, 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Any = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , )
38
1
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs("hub/hopper-medium-v2/unet/hor32", exist_ok=True) os.makedirs("hub/hopper-medium-v2/unet/hor128", exist_ok=True) os.makedirs("hub/hopper-medium-v2/value_function", exist_ok=True) def UpperCamelCase__ ( __magic_name__ : str ) -> Tuple: '''simple docstring''' if hor == 1_28: snake_case__ : Dict = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") snake_case__ : List[str] = (32, 1_28, 2_56) snake_case__ : Tuple = ("""UpResnetBlock1D""", """UpResnetBlock1D""") elif hor == 32: snake_case__ : Dict = ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""") snake_case__ : Any = (32, 64, 1_28, 2_56) snake_case__ : str = ("""UpResnetBlock1D""", """UpResnetBlock1D""", """UpResnetBlock1D""") snake_case__ : Any = torch.load(f"/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch" ) snake_case__ : List[str] = model.state_dict() snake_case__ : Optional[Any] = { """down_block_types""": down_block_types, """block_out_channels""": block_out_channels, """up_block_types""": up_block_types, """layers_per_block""": 1, """use_timestep_embedding""": True, """out_block_type""": """OutConv1DBlock""", """norm_num_groups""": 8, """downsample_each_block""": False, """in_channels""": 14, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """flip_sin_to_cos""": False, """freq_shift""": 1, """sample_size""": 6_55_36, """mid_block_type""": """MidResTemporalBlock1D""", """act_fn""": """mish""", } snake_case__ : Any = UNetaDModel(**__magic_name__ ) print(f"length of state dict: {len(state_dict.keys() )}" ) print(f"length of value function dict: {len(hf_value_function.state_dict().keys() )}" ) snake_case__ : Union[str, Any] = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): snake_case__ : Any = state_dict.pop(__magic_name__ ) hf_value_function.load_state_dict(__magic_name__ ) torch.save(hf_value_function.state_dict() , f"hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin" ) with open(f"hub/hopper-medium-v2/unet/hor{hor}/config.json" , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) def UpperCamelCase__ ( ) -> Optional[Any]: '''simple docstring''' snake_case__ : Tuple = { """in_channels""": 14, """down_block_types""": ("""DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D""", """DownResnetBlock1D"""), """up_block_types""": (), """out_block_type""": """ValueFunction""", """mid_block_type""": """ValueFunctionMidBlock1D""", """block_out_channels""": (32, 64, 1_28, 2_56), """layers_per_block""": 1, """downsample_each_block""": True, """sample_size""": 6_55_36, """out_channels""": 14, """extra_in_channels""": 0, """time_embedding_type""": """positional""", """use_timestep_embedding""": True, """flip_sin_to_cos""": False, """freq_shift""": 1, """norm_num_groups""": 8, """act_fn""": """mish""", } snake_case__ : Tuple = torch.load("""/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch""" ) snake_case__ : Optional[Any] = model snake_case__ : List[str] = UNetaDModel(**__magic_name__ ) print(f"length of state dict: {len(state_dict.keys() )}" ) print(f"length of value function dict: {len(hf_value_function.state_dict().keys() )}" ) snake_case__ : Union[str, Any] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): snake_case__ : List[str] = state_dict.pop(__magic_name__ ) hf_value_function.load_state_dict(__magic_name__ ) torch.save(hf_value_function.state_dict() , """hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin""" ) with open("""hub/hopper-medium-v2/value_function/config.json""" , """w""" ) as f: json.dump(__magic_name__ , __magic_name__ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
38
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : int = logging.get_logger(__name__) A_ : Any = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''resnet''' lowerCamelCase__ = ['''basic''', '''bottleneck'''] def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , __SCREAMING_SNAKE_CASE=[3, 4, 6, 3] , __SCREAMING_SNAKE_CASE="bottleneck" , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) snake_case__ : List[Any] = num_channels snake_case__ : str = embedding_size snake_case__ : List[Any] = hidden_sizes snake_case__ : Dict = depths snake_case__ : List[Any] = layer_type snake_case__ : int = hidden_act snake_case__ : Union[str, Any] = downsample_in_first_stage snake_case__ : Dict = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] snake_case__ , snake_case__ : Any = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names ) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = version.parse('''1.11''' ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __UpperCamelCase ( self ): return 1e-3
38
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Dict: '''simple docstring''' snake_case__ : int = botoa.client("""iam""" ) snake_case__ : Union[str, Any] = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=__magic_name__ , AssumeRolePolicyDocument=json.dumps(__magic_name__ , indent=2 ) ) snake_case__ : Dict = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=__magic_name__ , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(__magic_name__ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def UpperCamelCase__ ( __magic_name__ : Any ) -> Tuple: '''simple docstring''' snake_case__ : List[str] = botoa.client("""iam""" ) return iam_client.get_role(RoleName=__magic_name__ )["Role"]["Arn"] def UpperCamelCase__ ( ) -> Tuple: '''simple docstring''' snake_case__ : Union[str, Any] = _ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , __magic_name__ , ) snake_case__ : List[Any] = None if credentials_configuration == 0: snake_case__ : Dict = _ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) snake_case__ : List[str] = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) snake_case__ : List[str] = _ask_field("""AWS Access Key ID: """ ) snake_case__ : int = aws_access_key_id snake_case__ : Optional[Any] = _ask_field("""AWS Secret Access Key: """ ) snake_case__ : List[str] = aws_secret_access_key snake_case__ : Tuple = _ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) snake_case__ : Optional[int] = aws_region snake_case__ : int = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , __magic_name__ , ) if role_management == 0: snake_case__ : Optional[Any] = _ask_field("""Enter your IAM role name: """ ) else: snake_case__ : Optional[int] = """accelerate_sagemaker_execution_role""" print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(__magic_name__ ) snake_case__ : Dict = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Any = None if is_custom_docker_image: snake_case__ : str = _ask_field("""Enter your Docker image: """ , lambda __magic_name__ : str(__magic_name__ ).lower() ) snake_case__ : Tuple = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : List[Any] = None if is_sagemaker_inputs_enabled: snake_case__ : str = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Optional[int] = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Optional[Any] = None if is_sagemaker_metrics_enabled: snake_case__ : List[Any] = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Tuple = _ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) snake_case__ : Any = {} snake_case__ : List[Any] = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_dynamo: snake_case__ : str = """dynamo_""" snake_case__ : Tuple = _ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) snake_case__ : List[str] = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_custom_options: snake_case__ : str = _ask_options( """Which mode do you want to use?""" , __magic_name__ , lambda __magic_name__ : TORCH_DYNAMO_MODES[int(__magic_name__ )] , default="""default""" , ) snake_case__ : Union[str, Any] = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : str = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Dict = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: snake_case__ : List[str] = _ask_options( __magic_name__ , __magic_name__ , lambda __magic_name__ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(__magic_name__ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" snake_case__ : Optional[int] = _ask_field(__magic_name__ , lambda __magic_name__ : str(__magic_name__ ).lower() , default="""ml.p3.2xlarge""" ) snake_case__ : Dict = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): snake_case__ : Optional[Any] = _ask_field( """How many machines do you want use? [1]: """ , __magic_name__ , default=1 , ) snake_case__ : Union[str, Any] = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=__magic_name__ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=__magic_name__ , use_cpu=__magic_name__ , dynamo_config=__magic_name__ , eca_instance_type=__magic_name__ , profile=__magic_name__ , region=__magic_name__ , iam_role_name=__magic_name__ , mixed_precision=__magic_name__ , num_machines=__magic_name__ , sagemaker_inputs_file=__magic_name__ , sagemaker_metrics_file=__magic_name__ , )
38
'''simple docstring''' # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( "pipelines_utils", "0.22.0", "Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.", standard_warn=False, stacklevel=3, )
38
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) A_ : Optional[Any] = { "configuration_vision_encoder_decoder": ["VisionEncoderDecoderConfig", "VisionEncoderDecoderOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[Any] = ["VisionEncoderDecoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = ["TFVisionEncoderDecoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = ["FlaxVisionEncoderDecoderModel"] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys A_ : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
38
'''simple docstring''' import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self ): snake_case__ : str = [] def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_init_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_train_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_train_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_epoch_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_epoch_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_step_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_step_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_evaluate""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_predict""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_save""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_log""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_prediction_step""" ) @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Tuple = tempfile.mkdtemp() def __UpperCamelCase ( self ): shutil.rmtree(self.output_dir ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=False , **__SCREAMING_SNAKE_CASE ): # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. snake_case__ : List[Any] = RegressionDataset(length=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionDataset(length=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionModelConfig(a=__SCREAMING_SNAKE_CASE , b=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionPreTrainedModel(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = TrainingArguments(self.output_dir , disable_tqdm=__SCREAMING_SNAKE_CASE , report_to=[] , **__SCREAMING_SNAKE_CASE ) return Trainer( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , train_dataset=__SCREAMING_SNAKE_CASE , eval_dataset=__SCREAMING_SNAKE_CASE , callbacks=__SCREAMING_SNAKE_CASE , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) # Order doesn't matter snake_case__ : Tuple = sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : cb.__name__ if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else cb.__class__.__name__ ) snake_case__ : List[str] = sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : cb.__name__ if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else cb.__class__.__name__ ) for cba, cba in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(__SCREAMING_SNAKE_CASE , cba.__class__ ) elif not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(cba.__class__ , __SCREAMING_SNAKE_CASE ) else: self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = ["""on_init_end""", """on_train_begin"""] snake_case__ : Union[str, Any] = 0 snake_case__ : Dict = len(trainer.get_eval_dataloader() ) snake_case__ : Any = ["""on_prediction_step"""] * len(trainer.get_eval_dataloader() ) + ["""on_log""", """on_evaluate"""] for _ in range(trainer.state.num_train_epochs ): expected_events.append("""on_epoch_begin""" ) for _ in range(__SCREAMING_SNAKE_CASE ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append("""on_log""" ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append("""on_save""" ) expected_events.append("""on_epoch_end""" ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __UpperCamelCase ( self ): snake_case__ : Any = self.get_trainer() snake_case__ : str = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # Callbacks passed at init are added to the default callbacks snake_case__ : List[str] = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback snake_case__ : Optional[Any] = self.get_trainer(disable_tqdm=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = DEFAULT_CALLBACKS.copy() + [ProgressCallback] snake_case__ : int = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.remove(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = self.get_trainer() snake_case__ : List[str] = trainer.pop_callback(__SCREAMING_SNAKE_CASE ) self.assertEqual(cb.__class__ , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) trainer.add_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.insert(0 , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # We can also add, pop, or remove by instance snake_case__ : List[Any] = self.get_trainer() snake_case__ : List[str] = trainer.callback_handler.callbacks[0] trainer.remove_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.remove(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = self.get_trainer() snake_case__ : Any = trainer.callback_handler.callbacks[0] snake_case__ : Optional[Any] = trainer.pop_callback(__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) trainer.add_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.insert(0 , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action="""ignore""" , category=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # Independent log/save/eval snake_case__ : Dict = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() snake_case__ : int = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Any = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Tuple = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy="""steps""" ) trainer.train() snake_case__ : str = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Tuple = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy="""epoch""" ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # A bit of everything snake_case__ : Dict = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=1_0 , eval_steps=5 , evaluation_strategy="""steps""" , ) trainer.train() snake_case__ : Tuple = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # warning should be emitted for duplicated callbacks with patch("""transformers.trainer_callback.logger.warning""" ) as warn_mock: snake_case__ : List[str] = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(__SCREAMING_SNAKE_CASE ) in warn_mock.call_args[0][0]
38
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : List[str] = { "configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"], "tokenization_lxmert": ["LxmertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Optional[int] = ["LxmertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : int = [ "LxmertEncoder", "LxmertForPreTraining", "LxmertForQuestionAnswering", "LxmertModel", "LxmertPreTrainedModel", "LxmertVisualFeatureEncoder", "LxmertXLayer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLxmertForPreTraining", "TFLxmertMainLayer", "TFLxmertModel", "TFLxmertPreTrainedModel", "TFLxmertVisualFeatureEncoder", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys A_ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
38
'''simple docstring''' import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision 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 DPTImageProcessor class __snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=1_8 , __SCREAMING_SNAKE_CASE=3_0 , __SCREAMING_SNAKE_CASE=4_0_0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ): snake_case__ : Any = size if size is not None else {"""height""": 1_8, """width""": 1_8} snake_case__ : List[Any] = parent snake_case__ : int = batch_size snake_case__ : List[Any] = num_channels snake_case__ : str = image_size snake_case__ : Union[str, Any] = min_resolution snake_case__ : List[Any] = max_resolution snake_case__ : Tuple = do_resize snake_case__ : int = size snake_case__ : Tuple = do_normalize snake_case__ : Dict = image_mean snake_case__ : Union[str, Any] = image_std def __UpperCamelCase ( self ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = DPTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self ): snake_case__ : str = DPTImageProcessingTester(self ) @property def __UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_std""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """size""" ) ) def __UpperCamelCase ( self ): snake_case__ : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 1_8, """width""": 1_8} ) snake_case__ : List[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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input snake_case__ : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case__ : List[str] = image_processing(__SCREAMING_SNAKE_CASE , 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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case__ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input snake_case__ : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case__ : Any = image_processing(__SCREAMING_SNAKE_CASE , 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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case__ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input snake_case__ : List[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 snake_case__ : List[str] = image_processing(__SCREAMING_SNAKE_CASE , 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"""], ) , )
38
1
'''simple docstring''' import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class __snake_case : '''simple docstring''' @staticmethod def __UpperCamelCase ( *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): pass def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. A_ : str = ( "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png" ) @is_pipeline_test @require_torch @require_vision class __snake_case ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = pipeline( """document-question-answering""" , model=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = INVOICE_URL snake_case__ : Tuple = list(zip(*apply_tesseract(load_image(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """""" ) ) ) snake_case__ : Dict = """What is the placebo?""" snake_case__ : Dict = [ { """image""": load_image(__SCREAMING_SNAKE_CASE ), """question""": question, }, { """image""": image, """question""": question, }, { """image""": image, """question""": question, """word_boxes""": word_boxes, }, ] return dqa_pipeline, examples def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[int] = dqa_pipeline(__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ [ {"""score""": ANY(__SCREAMING_SNAKE_CASE ), """answer""": ANY(__SCREAMING_SNAKE_CASE ), """start""": ANY(__SCREAMING_SNAKE_CASE ), """end""": ANY(__SCREAMING_SNAKE_CASE )}, {"""score""": ANY(__SCREAMING_SNAKE_CASE ), """answer""": ANY(__SCREAMING_SNAKE_CASE ), """start""": ANY(__SCREAMING_SNAKE_CASE ), """end""": ANY(__SCREAMING_SNAKE_CASE )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def __UpperCamelCase ( self ): snake_case__ : Optional[int] = pipeline("""document-question-answering""" , model="""hf-internal-testing/tiny-random-layoutlmv2""" ) snake_case__ : Any = INVOICE_URL snake_case__ : int = """How many cats are there?""" snake_case__ : str = [ {"""score""": 0.0001, """answer""": """oy 2312/2019""", """start""": 3_8, """end""": 3_9}, {"""score""": 0.0001, """answer""": """oy 2312/2019 DUE""", """start""": 3_8, """end""": 4_0}, ] snake_case__ : Tuple = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = dqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , __SCREAMING_SNAKE_CASE ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably snake_case__ : Tuple = """./tests/fixtures/tests_samples/COCO/000000039769.png""" snake_case__ : Tuple = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual(__SCREAMING_SNAKE_CASE , [] ) # We can optionnally pass directly the words and bounding boxes snake_case__ : Tuple = """./tests/fixtures/tests_samples/COCO/000000039769.png""" snake_case__ : Optional[int] = [] snake_case__ : Optional[int] = [] snake_case__ : Any = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , words=__SCREAMING_SNAKE_CASE , boxes=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual(__SCREAMING_SNAKE_CASE , [] ) @slow @require_torch @require_detectrona @require_pytesseract def __UpperCamelCase ( self ): snake_case__ : Dict = pipeline( """document-question-answering""" , model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa""" , revision="""9977165""" , ) snake_case__ : int = INVOICE_URL snake_case__ : Tuple = """What is the invoice number?""" snake_case__ : str = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9944, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.0009, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ] , ) snake_case__ : int = dqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9944, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.0009, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ] , ) snake_case__ : List[Any] = dqa_pipeline( [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9944, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.0009, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def __UpperCamelCase ( self ): snake_case__ : int = pipeline( """document-question-answering""" , model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa""" , revision="""9977165""" , max_seq_len=5_0 , ) snake_case__ : Any = INVOICE_URL snake_case__ : Tuple = """What is the invoice number?""" snake_case__ : Union[str, Any] = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9974, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3}, {"""score""": 0.9948, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ] , ) snake_case__ : Dict = dqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9974, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3}, {"""score""": 0.9948, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ] , ) snake_case__ : List[str] = dqa_pipeline( [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9974, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3}, {"""score""": 0.9948, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = AutoTokenizer.from_pretrained( """impira/layoutlm-document-qa""" , revision="""3dc6de3""" , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = pipeline( """document-question-answering""" , model="""impira/layoutlm-document-qa""" , tokenizer=__SCREAMING_SNAKE_CASE , revision="""3dc6de3""" , ) snake_case__ : str = INVOICE_URL snake_case__ : Optional[int] = """What is the invoice number?""" snake_case__ : int = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.4251, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.0819, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3}, ] , ) snake_case__ : str = dqa_pipeline({"""image""": image, """question""": question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.4251, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.0819, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3}, ] , ) snake_case__ : List[str] = dqa_pipeline( [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.4251, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.0819, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3}, ] ] * 2 , ) snake_case__ : Any = list(zip(*apply_tesseract(load_image(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """""" ) ) ) # This model should also work if `image` is set to None snake_case__ : Optional[int] = dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.4251, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.0819, """answer""": """1110212019""", """start""": 2_3, """end""": 2_3}, ] , ) @slow @require_torch @require_pytesseract @require_vision def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = AutoTokenizer.from_pretrained( """impira/layoutlm-document-qa""" , revision="""3dc6de3""" , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = pipeline( """document-question-answering""" , model="""impira/layoutlm-document-qa""" , tokenizer=__SCREAMING_SNAKE_CASE , revision="""3dc6de3""" , max_seq_len=5_0 , ) snake_case__ : str = INVOICE_URL snake_case__ : Optional[Any] = """What is the invoice number?""" snake_case__ : List[str] = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9999, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.9998, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ] , ) snake_case__ : Dict = dqa_pipeline( [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}] , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {"""score""": 0.9999, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.9998, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ] ] * 2 , ) snake_case__ : Any = list(zip(*apply_tesseract(load_image(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , """""" ) ) ) # This model should also work if `image` is set to None snake_case__ : Optional[Any] = dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {"""score""": 0.9999, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, {"""score""": 0.9998, """answer""": """us-001""", """start""": 1_6, """end""": 1_6}, ] , ) @slow @require_torch def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = pipeline( """document-question-answering""" , model="""naver-clova-ix/donut-base-finetuned-docvqa""" , tokenizer=AutoTokenizer.from_pretrained("""naver-clova-ix/donut-base-finetuned-docvqa""" ) , feature_extractor="""naver-clova-ix/donut-base-finetuned-docvqa""" , ) snake_case__ : Dict = INVOICE_URL snake_case__ : Dict = """What is the invoice number?""" snake_case__ : Tuple = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [{"""answer""": """us-001"""}] ) @require_tf @unittest.skip("""Document question answering not implemented in TF""" ) def __UpperCamelCase ( self ): pass
38
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig 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 TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Dict = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """embed_dim""" ) ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """num_heads""" ) ) class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=[1_6, 4_8, 9_6] , __SCREAMING_SNAKE_CASE=[1, 3, 6] , __SCREAMING_SNAKE_CASE=[1, 2, 1_0] , __SCREAMING_SNAKE_CASE=[7, 3, 3] , __SCREAMING_SNAKE_CASE=[4, 2, 2] , __SCREAMING_SNAKE_CASE=[2, 1, 1] , __SCREAMING_SNAKE_CASE=[2, 2, 2] , __SCREAMING_SNAKE_CASE=[False, False, True] , __SCREAMING_SNAKE_CASE=[0.0, 0.0, 0.0] , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=2 , ): snake_case__ : List[str] = parent snake_case__ : Tuple = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : List[Any] = patch_sizes snake_case__ : Optional[int] = patch_stride snake_case__ : Optional[Any] = patch_padding snake_case__ : Any = is_training snake_case__ : int = use_labels snake_case__ : Dict = num_labels snake_case__ : Optional[Any] = num_channels snake_case__ : Optional[Any] = embed_dim snake_case__ : Optional[int] = num_heads snake_case__ : Optional[int] = stride_kv snake_case__ : int = depth snake_case__ : Optional[Any] = cls_token snake_case__ : List[Any] = attention_drop_rate snake_case__ : Union[str, Any] = initializer_range snake_case__ : List[Any] = layer_norm_eps def __UpperCamelCase ( self ): snake_case__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[Any] = None if self.use_labels: # create a random int32 tensor of given shape snake_case__ : List[str] = ids_tensor([self.batch_size] , self.num_labels ) snake_case__ : List[str] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = TFCvtModel(config=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = model(__SCREAMING_SNAKE_CASE , training=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = (self.image_size, self.image_size) snake_case__ , snake_case__ : str = image_size[0], image_size[1] for i in range(len(self.depth ) ): snake_case__ : Any = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) snake_case__ : Optional[int] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = self.num_labels snake_case__ : str = TFCvtForImageClassification(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , training=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Union[str, Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () lowerCamelCase__ = ( {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification} if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = TFCvtModelTester(self ) snake_case__ : Any = TFCvtConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason="""Cvt does not output attentions""" ) def __UpperCamelCase ( self ): pass @unittest.skip(reason="""Cvt does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass @unittest.skip(reason="""Cvt does not support input and output embeddings""" ) def __UpperCamelCase ( self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) def __UpperCamelCase ( self ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def __UpperCamelCase ( self ): super().test_keras_fit() @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""" ) def __UpperCamelCase ( self ): snake_case__ : List[str] = tf.keras.mixed_precision.Policy("""mixed_float16""" ) tf.keras.mixed_precision.set_global_policy(__SCREAMING_SNAKE_CASE ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("""float32""" ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Optional[Any] = [*signature.parameters.keys()] snake_case__ : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): def check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[int] = outputs.hidden_states snake_case__ : Tuple = len(self.model_tester.depth ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : List[Any] = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[str] = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def __UpperCamelCase ( self ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : str = TFCvtModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class __snake_case ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCamelCase ( self ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) snake_case__ : Union[str, Any] = self.default_image_processor snake_case__ : int = prepare_img() snake_case__ : Dict = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) # forward pass snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE ) # verify the logits snake_case__ : str = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : int = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
1
'''simple docstring''' from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup A_ : Optional[int] = "https://www.indeed.co.in/jobs?q=mobile+app+development&l=" def UpperCamelCase__ ( __magic_name__ : str = "mumbai" ) -> Generator[tuple[str, str], None, None]: '''simple docstring''' snake_case__ : List[str] = 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"""} ): snake_case__ : Any = job.find("""a""" , attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() snake_case__ : List[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]}')
38
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. snake_case__ : int = [[1, 2, 4], [1, 2, 3, 4]] snake_case__ : Any = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) self.assertTrue(isinstance(dc.token_ids , __SCREAMING_SNAKE_CASE ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __UpperCamelCase ( self ): # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). snake_case__ : Union[str, Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) # fails here def __UpperCamelCase ( self ): snake_case__ : List[str] = [[1, 2, 3], [1, 2, 4]] snake_case__ : Optional[int] = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ , snake_case__ : Any = dc.update(1 ) snake_case__ : Any = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : Tuple = dc.update(2 ) snake_case__ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = dc.update(3 ) snake_case__ : List[str] = stepped is True and completed is True and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] snake_case__ : int = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ , snake_case__ : str = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : Dict = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
38
1
'''simple docstring''' import os from math import logaa def UpperCamelCase__ ( __magic_name__ : str = "base_exp.txt" ) -> int: '''simple docstring''' snake_case__ : float = 0 snake_case__ : Union[str, Any] = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(__magic_name__ ) , __magic_name__ ) ) ): snake_case__ , snake_case__ : Tuple = list(map(__magic_name__ , line.split(""",""" ) ) ) if x * logaa(__magic_name__ ) > largest: snake_case__ : Optional[Any] = x * logaa(__magic_name__ ) snake_case__ : int = i + 1 return result if __name__ == "__main__": print(solution())
38
'''simple docstring''' import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[int] = logging.get_logger(__name__) A_ : Tuple = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''segformer''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=[2, 2, 2, 2] , __SCREAMING_SNAKE_CASE=[8, 4, 2, 1] , __SCREAMING_SNAKE_CASE=[3_2, 6_4, 1_6_0, 2_5_6] , __SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , __SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , __SCREAMING_SNAKE_CASE=[1, 2, 5, 8] , __SCREAMING_SNAKE_CASE=[4, 4, 4, 4] , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1e-6 , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=2_5_5 , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , __SCREAMING_SNAKE_CASE , ) snake_case__ : Dict = num_channels snake_case__ : Optional[Any] = num_encoder_blocks snake_case__ : Any = depths snake_case__ : Optional[int] = sr_ratios snake_case__ : Tuple = hidden_sizes snake_case__ : List[str] = patch_sizes snake_case__ : str = strides snake_case__ : Optional[int] = mlp_ratios snake_case__ : Optional[Any] = num_attention_heads snake_case__ : Dict = hidden_act snake_case__ : Optional[int] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : List[Any] = classifier_dropout_prob snake_case__ : int = initializer_range snake_case__ : List[str] = drop_path_rate snake_case__ : int = layer_norm_eps snake_case__ : List[Any] = decoder_hidden_size snake_case__ : List[Any] = kwargs.get("""reshape_last_stage""" , __SCREAMING_SNAKE_CASE ) snake_case__ : Dict = semantic_loss_ignore_index class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = version.parse('''1.11''' ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __UpperCamelCase ( self ): return 1e-4 @property def __UpperCamelCase ( self ): return 1_2
38
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL A_ : Tuple = logging.get_logger(__name__) def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : int ) -> int: '''simple docstring''' snake_case__ : List[Any] = b.T snake_case__ : Union[str, Any] = np.sum(np.square(__magic_name__ ) , axis=1 ) snake_case__ : List[Any] = np.sum(np.square(__magic_name__ ) , axis=0 ) snake_case__ : Dict = np.matmul(__magic_name__ , __magic_name__ ) snake_case__ : List[str] = aa[:, None] - 2 * ab + ba[None, :] return d def UpperCamelCase__ ( __magic_name__ : Union[str, Any] , __magic_name__ : Any ) -> Union[str, Any]: '''simple docstring''' snake_case__ : List[str] = x.reshape(-1 , 3 ) snake_case__ : Optional[int] = squared_euclidean_distance(__magic_name__ , __magic_name__ ) return np.argmin(__magic_name__ , axis=1 ) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''pixel_values'''] def __init__( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = True , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) snake_case__ : int = size if size is not None else {"""height""": 2_5_6, """width""": 2_5_6} snake_case__ : Optional[Any] = get_size_dict(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = np.array(__SCREAMING_SNAKE_CASE ) if clusters is not None else None snake_case__ : Tuple = do_resize snake_case__ : int = size snake_case__ : int = resample snake_case__ : List[Any] = do_normalize snake_case__ : Any = do_color_quantize def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): snake_case__ : Any = get_size_dict(__SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f"Size dictionary must contain both height and width keys. Got {size.keys()}" ) return resize( __SCREAMING_SNAKE_CASE , size=(size["""height"""], size["""width"""]) , resample=__SCREAMING_SNAKE_CASE , data_format=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , ): snake_case__ : Any = rescale(image=__SCREAMING_SNAKE_CASE , scale=1 / 127.5 , data_format=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = image - 1 return image def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **__SCREAMING_SNAKE_CASE , ): snake_case__ : str = do_resize if do_resize is not None else self.do_resize snake_case__ : List[str] = size if size is not None else self.size snake_case__ : int = get_size_dict(__SCREAMING_SNAKE_CASE ) snake_case__ : str = resample if resample is not None else self.resample snake_case__ : str = do_normalize if do_normalize is not None else self.do_normalize snake_case__ : Optional[Any] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize snake_case__ : Any = clusters if clusters is not None else self.clusters snake_case__ : List[Any] = np.array(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = make_list_of_images(__SCREAMING_SNAKE_CASE ) if not valid_images(__SCREAMING_SNAKE_CASE ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_color_quantize and clusters is None: raise ValueError("""Clusters must be specified if do_color_quantize is True.""" ) # All transformations expect numpy arrays. snake_case__ : Union[str, Any] = [to_numpy_array(__SCREAMING_SNAKE_CASE ) for image in images] if do_resize: snake_case__ : Union[str, Any] = [self.resize(image=__SCREAMING_SNAKE_CASE , size=__SCREAMING_SNAKE_CASE , resample=__SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: snake_case__ : List[Any] = [self.normalize(image=__SCREAMING_SNAKE_CASE ) for image in images] if do_color_quantize: snake_case__ : int = [to_channel_dimension_format(__SCREAMING_SNAKE_CASE , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) snake_case__ : Optional[Any] = np.array(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = color_quantize(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) snake_case__ : List[Any] = images.shape[0] snake_case__ : List[str] = images.reshape(__SCREAMING_SNAKE_CASE , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. snake_case__ : Optional[int] = list(__SCREAMING_SNAKE_CASE ) else: snake_case__ : Dict = [to_channel_dimension_format(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for image in images] snake_case__ : Optional[int] = {"""input_ids""": images} return BatchFeature(data=__SCREAMING_SNAKE_CASE , tensor_type=__SCREAMING_SNAKE_CASE )
38
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : List[Any]=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : str = None if token is not None: snake_case__ : str = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : List[Any] = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" snake_case__ : str = requests.get(__magic_name__ , headers=__magic_name__ ).json() snake_case__ : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) snake_case__ : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(__magic_name__ ): snake_case__ : Tuple = requests.get(url + f"&page={i + 2}" , headers=__magic_name__ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any]=None ) -> List[str]: '''simple docstring''' snake_case__ : Optional[Any] = None if token is not None: snake_case__ : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : Dict = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" snake_case__ : Union[str, Any] = requests.get(__magic_name__ , headers=__magic_name__ ).json() snake_case__ : Dict = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) snake_case__ : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(__magic_name__ ): snake_case__ : Dict = requests.get(url + f"&page={i + 2}" , headers=__magic_name__ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Dict ) -> Dict: '''simple docstring''' snake_case__ : Optional[Any] = None if token is not None: snake_case__ : Dict = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : str = requests.get(__magic_name__ , headers=__magic_name__ , allow_redirects=__magic_name__ ) snake_case__ : Any = result.headers["""Location"""] snake_case__ : Tuple = requests.get(__magic_name__ , allow_redirects=__magic_name__ ) snake_case__ : int = os.path.join(__magic_name__ , f"{artifact_name}.zip" ) with open(__magic_name__ , """wb""" ) as fp: fp.write(response.content ) def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : str=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Any = [] snake_case__ : Union[str, Any] = [] snake_case__ : Any = None with zipfile.ZipFile(__magic_name__ ) as z: for filename in z.namelist(): if not os.path.isdir(__magic_name__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(__magic_name__ ) as f: for line in f: snake_case__ : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs snake_case__ : str = line[: line.index(""": """ )] snake_case__ : Optional[int] = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed snake_case__ : Dict = line[len("""FAILED """ ) :] failed_tests.append(__magic_name__ ) elif filename == "job_name.txt": snake_case__ : Optional[Any] = line if len(__magic_name__ ) != len(__magic_name__ ): raise ValueError( f"`errors` and `failed_tests` should have the same number of elements. Got {len(__magic_name__ )} for `errors` " f"and {len(__magic_name__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" """ problem.""" ) snake_case__ : Optional[Any] = None if job_name and job_links: snake_case__ : Optional[Any] = job_links.get(__magic_name__ , __magic_name__ ) # A list with elements of the form (line of error, error, failed test) snake_case__ : List[Any] = [x + [y] + [job_link] for x, y in zip(__magic_name__ , __magic_name__ )] return result def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : Union[str, Any]=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : str = [] snake_case__ : Dict = [os.path.join(__magic_name__ , __magic_name__ ) for p in os.listdir(__magic_name__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(__magic_name__ , job_links=__magic_name__ ) ) return errors def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : str=None ) -> List[Any]: '''simple docstring''' snake_case__ : Any = Counter() counter.update([x[1] for x in logs] ) snake_case__ : Dict = counter.most_common() snake_case__ : Any = {} for error, count in counts: if error_filter is None or error not in error_filter: snake_case__ : int = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} snake_case__ : Union[str, Any] = dict(sorted(r.items() , key=lambda __magic_name__ : item[1]["count"] , reverse=__magic_name__ ) ) return r def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> List[Any]: '''simple docstring''' snake_case__ : str = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): snake_case__ : Tuple = test.split("""/""" )[2] else: snake_case__ : Any = None return test def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : Union[str, Any]=None ) -> List[str]: '''simple docstring''' snake_case__ : List[str] = [(x[0], x[1], get_model(x[2] )) for x in logs] snake_case__ : List[Any] = [x for x in logs if x[2] is not None] snake_case__ : Any = {x[2] for x in logs} snake_case__ : Optional[Any] = {} for test in tests: snake_case__ : str = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) snake_case__ : Optional[int] = counter.most_common() snake_case__ : Optional[int] = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} snake_case__ : int = sum(error_counts.values() ) if n_errors > 0: snake_case__ : str = {"""count""": n_errors, """errors""": error_counts} snake_case__ : Union[str, Any] = dict(sorted(r.items() , key=lambda __magic_name__ : item[1]["count"] , reverse=__magic_name__ ) ) return r def UpperCamelCase__ ( __magic_name__ : int ) -> Optional[int]: '''simple docstring''' snake_case__ : Optional[Any] = """| no. | error | status |""" snake_case__ : int = """|-:|:-|:-|""" snake_case__ : int = [header, sep] for error in reduced_by_error: snake_case__ : Union[str, Any] = reduced_by_error[error]["""count"""] snake_case__ : Dict = f"| {count} | {error[:1_00]} | |" lines.append(__magic_name__ ) return "\n".join(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> List[Any]: '''simple docstring''' snake_case__ : List[Any] = """| model | no. of errors | major error | count |""" snake_case__ : Optional[int] = """|-:|-:|-:|-:|""" snake_case__ : Dict = [header, sep] for model in reduced_by_model: snake_case__ : Tuple = reduced_by_model[model]["""count"""] snake_case__ , snake_case__ : Tuple = list(reduced_by_model[model]["""errors"""].items() )[0] snake_case__ : Optional[int] = f"| {model} | {count} | {error[:60]} | {_count} |" lines.append(__magic_name__ ) return "\n".join(__magic_name__ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") A_ : int = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) A_ : Optional[int] = get_job_links(args.workflow_run_id, token=args.token) A_ : Optional[Any] = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: A_ : int = k.find(" / ") A_ : List[Any] = k[index + len(" / ") :] A_ : List[str] = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) A_ : int = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) A_ : str = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error A_ : List[str] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors A_ : Any = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) A_ : Any = reduce_by_error(errors) A_ : Union[str, Any] = reduce_by_model(errors) A_ : Any = make_github_table(reduced_by_error) A_ : Optional[Any] = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
38
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): snake_case__ : str = path_or_paths snake_case__ : Any = split if split or isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else """train""" snake_case__ : int = features snake_case__ : Optional[Any] = cache_dir snake_case__ : List[str] = keep_in_memory snake_case__ : Optional[Any] = streaming snake_case__ : Optional[int] = num_proc snake_case__ : List[str] = kwargs @abstractmethod def __UpperCamelCase ( self ): pass class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): snake_case__ : str = features snake_case__ : Tuple = cache_dir snake_case__ : List[Any] = keep_in_memory snake_case__ : Optional[int] = streaming snake_case__ : str = num_proc snake_case__ : Tuple = kwargs @abstractmethod def __UpperCamelCase ( self ): pass
38
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version A_ : Tuple = get_logger(__name__) class __snake_case : '''simple docstring''' lowerCamelCase__ = '''dummy_data''' lowerCamelCase__ = '''datasets''' lowerCamelCase__ = False def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , ): snake_case__ : List[Any] = 0 snake_case__ : Union[str, Any] = dataset_name snake_case__ : Optional[int] = cache_dir snake_case__ : Union[str, Any] = use_local_dummy_data snake_case__ : int = config # download_callbacks take a single url as input snake_case__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root snake_case__ : Union[str, Any] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general snake_case__ : Union[str, Any] = str(__SCREAMING_SNAKE_CASE ) # to be downloaded snake_case__ : List[str] = None snake_case__ : List[str] = None @property def __UpperCamelCase ( self ): if self._dummy_file is None: snake_case__ : List[str] = self.download_dummy_data() return self._dummy_file @property def __UpperCamelCase ( self ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("""dummy""" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("""dummy""" , self.version_name ) @property def __UpperCamelCase ( self ): return os.path.join(self.dummy_data_folder , """dummy_data.zip""" ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) snake_case__ : Optional[int] = cached_path( __SCREAMING_SNAKE_CASE , cache_dir=self.cache_dir , extract_compressed_file=__SCREAMING_SNAKE_CASE , force_extract=__SCREAMING_SNAKE_CASE ) return os.path.join(__SCREAMING_SNAKE_CASE , self.dummy_file_name ) @property def __UpperCamelCase ( self ): return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __UpperCamelCase ( self ): if self._bucket_url is None: snake_case__ : List[str] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , """/""" ) ) return self._bucket_url @property def __UpperCamelCase ( self ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , """/""" ).split("""/""" )[:-1] ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): if self.load_existing_dummy_data: # dummy data is downloaded and tested snake_case__ : List[Any] = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned snake_case__ : List[Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return self.create_dummy_data_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ): return self.create_dummy_data_list(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return self.create_dummy_data_single(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): return self.download_and_extract(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return self.download_and_extract(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): return path def __UpperCamelCase ( self ): return {} def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for single_url in single_urls: download_callback(__SCREAMING_SNAKE_CASE ) else: snake_case__ : List[str] = single_urls download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = [os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(Path(__SCREAMING_SNAKE_CASE ).name ) ) for x in single_urls] else: snake_case__ : List[Any] = single_urls snake_case__ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(Path(__SCREAMING_SNAKE_CASE ).name ) ) snake_case__ : Optional[int] = value # make sure that values are unique if all(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique snake_case__ : List[Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one snake_case__ : Tuple = all(bool(re.findall("""[0-9]{3,}-of-[0-9]{3,}""" , __SCREAMING_SNAKE_CASE ) ) for url in data_url ) snake_case__ : List[Any] = all( url.startswith("""https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed""" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): snake_case__ : List[str] = [data_url[0]] * len(__SCREAMING_SNAKE_CASE ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case__ : List[Any] = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(single_url.split("""/""" )[-1] ) ) dummy_data_list.append(__SCREAMING_SNAKE_CASE ) return dummy_data_list def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for download_callback in self.download_callbacks: download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case__ : Any = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(data_url.split("""/""" )[-1] ) ) if os.path.exists(__SCREAMING_SNAKE_CASE ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): def _iter_archive_members(__SCREAMING_SNAKE_CASE ): # this preserves the order of the members inside the ZIP archive snake_case__ : List[str] = Path(self.dummy_file ).parent snake_case__ : Dict = path.relative_to(__SCREAMING_SNAKE_CASE ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: snake_case__ : Optional[int] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = Path(__SCREAMING_SNAKE_CASE ) snake_case__ : int = _iter_archive_members(__SCREAMING_SNAKE_CASE ) if self.use_local_dummy_data else path.rglob("""*""" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((""".""", """__""") ): yield file_path.relative_to(__SCREAMING_SNAKE_CASE ).as_posix(), file_path.open("""rb""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[int] = [paths] for path in paths: if os.path.isfile(__SCREAMING_SNAKE_CASE ): if os.path.basename(__SCREAMING_SNAKE_CASE ).startswith((""".""", """__""") ): return yield path else: for dirpath, dirnames, filenames in os.walk(__SCREAMING_SNAKE_CASE ): if os.path.basename(__SCREAMING_SNAKE_CASE ).startswith((""".""", """__""") ): continue dirnames.sort() for filename in sorted(__SCREAMING_SNAKE_CASE ): if filename.startswith((""".""", """__""") ): continue yield os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
38
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging A_ : Dict = logging.get_logger(__name__) A_ : List[str] = { "weiweishi/roc-bert-base-zh": "https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''roc_bert''' def __init__( self , __SCREAMING_SNAKE_CASE=3_0_5_2_2 , __SCREAMING_SNAKE_CASE=7_6_8 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=3_0_7_2 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE="absolute" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=7_6_8 , __SCREAMING_SNAKE_CASE=9_1_0 , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=2_4_8_5_8 , __SCREAMING_SNAKE_CASE=True , **__SCREAMING_SNAKE_CASE , ): snake_case__ : List[str] = vocab_size snake_case__ : Optional[Any] = max_position_embeddings snake_case__ : Optional[int] = hidden_size snake_case__ : Dict = num_hidden_layers snake_case__ : Optional[int] = num_attention_heads snake_case__ : str = intermediate_size snake_case__ : List[str] = hidden_act snake_case__ : Optional[Any] = hidden_dropout_prob snake_case__ : int = attention_probs_dropout_prob snake_case__ : Optional[int] = initializer_range snake_case__ : Any = type_vocab_size snake_case__ : Dict = layer_norm_eps snake_case__ : Optional[Any] = use_cache snake_case__ : List[Any] = enable_pronunciation snake_case__ : Tuple = enable_shape snake_case__ : List[str] = pronunciation_embed_dim snake_case__ : List[str] = pronunciation_vocab_size snake_case__ : int = shape_embed_dim snake_case__ : Dict = shape_vocab_size snake_case__ : int = concat_input snake_case__ : Optional[int] = position_embedding_type snake_case__ : int = classifier_dropout super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
38
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = IFImgaImgSuperResolutionPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def __UpperCamelCase ( self ): return self._get_superresolution_dummy_components() def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): snake_case__ : List[Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case__ : Tuple = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = floats_tensor((1, 3, 1_6, 1_6) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : int = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __UpperCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __UpperCamelCase ( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __UpperCamelCase ( self ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def __UpperCamelCase ( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __UpperCamelCase ( self ): self._test_save_load_local() def __UpperCamelCase ( self ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
38
1
'''simple docstring''' import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Optional[int] = logging.get_logger() # the current default level is logging.WARNING snake_case__ : Union[str, Any] = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = logging.get_verbosity() snake_case__ : Optional[int] = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) snake_case__ : str = """Testing 1, 2, 3""" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: logger.warning(__SCREAMING_SNAKE_CASE ) self.assertEqual(cl.out , msg + """\n""" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: logger.warning(__SCREAMING_SNAKE_CASE ) self.assertEqual(cl.out , """""" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: logger.warning(__SCREAMING_SNAKE_CASE ) self.assertEqual(cl.out , msg + """\n""" ) # restore to the original level logging.set_verbosity(__SCREAMING_SNAKE_CASE ) @mockenv(TRANSFORMERS_VERBOSITY="""error""" ) def __UpperCamelCase ( self ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var snake_case__ : List[Any] = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) snake_case__ : Any = os.getenv("""TRANSFORMERS_VERBOSITY""" , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = logging.log_levels[env_level_str] snake_case__ : str = logging.get_verbosity() self.assertEqual( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , f"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level snake_case__ : Union[str, Any] = """""" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="""super-error""" ) def __UpperCamelCase ( self ): # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() snake_case__ : Tuple = logging.logging.getLogger() with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: # this action activates the env var logging.get_logger("""transformers.models.bart.tokenization_bart""" ) self.assertIn("""Unknown option TRANSFORMERS_VERBOSITY=super-error""" , cl.out ) # no need to restore as nothing was changed def __UpperCamelCase ( self ): # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() snake_case__ : str = logging.get_logger("""transformers.models.bart.tokenization_bart""" ) snake_case__ : Dict = """Testing 1, 2, 3""" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""1""" ): # nothing should be logged as env var disables this method with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: logger.warning_advice(__SCREAMING_SNAKE_CASE ) self.assertEqual(cl.out , """""" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""""" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(__SCREAMING_SNAKE_CASE ) as cl: logger.warning_advice(__SCREAMING_SNAKE_CASE ) self.assertEqual(cl.out , msg + """\n""" ) def UpperCamelCase__ ( ) -> str: '''simple docstring''' disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
38
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu A_ : Dict = [ "EAGER", "AOT_EAGER", "INDUCTOR", "NVFUSER", "AOT_NVFUSER", "AOT_CUDAGRAPHS", "OFI", "FX2TRT", "ONNXRT", "IPEX", ] def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : List[Any]=None , __magic_name__ : List[str]=None , __magic_name__ : List[str]=None ) -> Dict: '''simple docstring''' snake_case__ : Optional[int] = True while ask_again: snake_case__ : Optional[Any] = input(__magic_name__ ) try: if default is not None and len(__magic_name__ ) == 0: return default return convert_value(__magic_name__ ) if convert_value is not None else result except Exception: if error_message is not None: print(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Any=[] , __magic_name__ : Optional[int]=None , __magic_name__ : int=0 ) -> Optional[int]: '''simple docstring''' snake_case__ : Union[str, Any] = BulletMenu(__magic_name__ , __magic_name__ ) snake_case__ : Optional[Any] = menu.run(default_choice=__magic_name__ ) return convert_value(__magic_name__ ) if convert_value is not None else result def UpperCamelCase__ ( __magic_name__ : Any ) -> int: '''simple docstring''' snake_case__ : Tuple = int(__magic_name__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def UpperCamelCase__ ( __magic_name__ : str ) -> Tuple: '''simple docstring''' snake_case__ : List[Any] = int(__magic_name__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> List[Any]: '''simple docstring''' snake_case__ : Union[str, Any] = int(__magic_name__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def UpperCamelCase__ ( __magic_name__ : List[str] ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Optional[Any] = int(__magic_name__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> List[Any]: '''simple docstring''' snake_case__ : Optional[Any] = int(__magic_name__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> Tuple: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class __snake_case ( argparse.RawDescriptionHelpFormatter ): '''simple docstring''' def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : str = usage.replace("""<command> [<args>] """ , """""" ) return usage
38
1
'''simple docstring''' class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): # we need a list not a string, so do something to change the type snake_case__ : int = arr.split(""",""" ) def __UpperCamelCase ( self ): snake_case__ : str = [int(self.array[0] )] * len(self.array ) snake_case__ : Optional[int] = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): snake_case__ : Union[str, Any] = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) snake_case__ : str = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": A_ : Dict = input("please input some numbers:") A_ : Dict = SubArray(whole_array) A_ : Dict = array.solve_sub_array() print(("the results is:", re))
38
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( __magic_name__ : list ) -> float: '''simple docstring''' if not nums: raise ValueError("""List is empty""" ) return sum(__magic_name__ ) / len(__magic_name__ ) if __name__ == "__main__": import doctest doctest.testmod()
38
1
'''simple docstring''' import math def UpperCamelCase__ ( __magic_name__ : float , __magic_name__ : float ) -> float: '''simple docstring''' return math.pow(__magic_name__ , 2 ) - a def UpperCamelCase__ ( __magic_name__ : float ) -> float: '''simple docstring''' return 2 * x def UpperCamelCase__ ( __magic_name__ : float ) -> float: '''simple docstring''' snake_case__ : Optional[int] = 2.0 while start <= a: snake_case__ : Any = math.pow(__magic_name__ , 2 ) return start def UpperCamelCase__ ( __magic_name__ : float , __magic_name__ : int = 99_99 , __magic_name__ : float = 0.00_0000_0000_0001 ) -> float: '''simple docstring''' if a < 0: raise ValueError("""math domain error""" ) snake_case__ : Tuple = get_initial_point(__magic_name__ ) for _ in range(__magic_name__ ): snake_case__ : Union[str, Any] = value snake_case__ : int = value - fx(__magic_name__ , __magic_name__ ) / fx_derivative(__magic_name__ ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
38
'''simple docstring''' from __future__ import annotations A_ : str = "Muhammad Umer Farooq" A_ : Optional[Any] = "MIT" A_ : int = "1.0.0" A_ : int = "Muhammad Umer Farooq" A_ : int = "[email protected]" A_ : Dict = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): super().__init__() snake_case__ : list[str] = [] snake_case__ : List[Any] = domain def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: snake_case__ : str = parse.urljoin(self.domain , __SCREAMING_SNAKE_CASE ) self.urls.append(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return ".".join(get_sub_domain_name(__magic_name__ ).split(""".""" )[-2:] ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return parse.urlparse(__magic_name__ ).netloc def UpperCamelCase__ ( __magic_name__ : str = "https://github.com" ) -> list[str]: '''simple docstring''' snake_case__ : List[str] = get_domain_name(__magic_name__ ) # Initialize the parser snake_case__ : Optional[Any] = Parser(__magic_name__ ) try: # Open URL snake_case__ : Any = requests.get(__magic_name__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through snake_case__ : List[str] = set() for link in parser.urls: # open URL. # read = requests.get(link) try: snake_case__ : Tuple = requests.get(__magic_name__ ) # Get the valid email. snake_case__ : List[str] = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(__magic_name__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(__magic_name__ ) if __name__ == "__main__": A_ : str = emails_from_url("https://github.com") print(F'{len(emails)} emails found:') print("\n".join(sorted(emails)))
38
1
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( __magic_name__ : int ) -> list[int]: '''simple docstring''' snake_case__ : Optional[Any] = [True] * limit snake_case__ : Dict = False snake_case__ : Optional[Any] = False snake_case__ : Any = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): snake_case__ : Tuple = i * 2 while index < limit: snake_case__ : Any = False snake_case__ : int = index + i snake_case__ : Tuple = [2] for i in range(3 , __magic_name__ , 2 ): if is_prime[i]: primes.append(__magic_name__ ) return primes def UpperCamelCase__ ( __magic_name__ : int = 1_00_00_00 ) -> int: '''simple docstring''' snake_case__ : Union[str, Any] = prime_sieve(__magic_name__ ) snake_case__ : Tuple = 0 snake_case__ : int = 0 for i in range(len(__magic_name__ ) ): for j in range(i + length , len(__magic_name__ ) ): snake_case__ : Any = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: snake_case__ : Optional[Any] = j - i snake_case__ : List[Any] = sol return largest if __name__ == "__main__": print(F'{solution() = }')
38
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> Tuple: '''simple docstring''' if not head: return True # split the list to two parts snake_case__ , snake_case__ : Dict = head.next, head while fast and fast.next: snake_case__ : Any = fast.next.next snake_case__ : int = slow.next snake_case__ : Dict = slow.next snake_case__ : List[str] = None # Don't forget here! But forget still works! # reverse the second part snake_case__ : Tuple = None while second: snake_case__ : Tuple = second.next snake_case__ : Any = node snake_case__ : str = second snake_case__ : Optional[Any] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False snake_case__ : List[Any] = node.next snake_case__ : int = head.next return True def UpperCamelCase__ ( __magic_name__ : Any ) -> Optional[Any]: '''simple docstring''' if not head or not head.next: return True # 1. Get the midpoint (slow) snake_case__ : List[Any] = head while fast and fast.next: snake_case__ , snake_case__ : Any = fast.next.next, slow.next # 2. Push the second half into the stack snake_case__ : Tuple = [slow.val] while slow.next: snake_case__ : Optional[Any] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False snake_case__ : str = cur.next return True def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Tuple: '''simple docstring''' if not head or not head.next: return True snake_case__ : int = {} snake_case__ : Union[str, Any] = 0 while head: if head.val in d: d[head.val].append(__magic_name__ ) else: snake_case__ : Tuple = [pos] snake_case__ : Optional[Any] = head.next pos += 1 snake_case__ : int = pos - 1 snake_case__ : str = 0 for v in d.values(): if len(__magic_name__ ) % 2 != 0: middle += 1 else: snake_case__ : List[str] = 0 for i in range(0 , len(__magic_name__ ) ): if v[i] + v[len(__magic_name__ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
38
1
'''simple docstring''' import functools from typing import Any def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : list[str] ) -> bool: '''simple docstring''' if not isinstance(__magic_name__ , __magic_name__ ) or len(__magic_name__ ) == 0: raise ValueError("""the string should be not empty string""" ) if not isinstance(__magic_name__ , __magic_name__ ) or not all( isinstance(__magic_name__ , __magic_name__ ) and len(__magic_name__ ) > 0 for item in words ): raise ValueError("""the words should be a list of non-empty strings""" ) # Build trie snake_case__ : dict[str, Any] = {} snake_case__ : Optional[Any] = """WORD_KEEPER""" for word in words: snake_case__ : Any = trie for c in word: if c not in trie_node: snake_case__ : Dict = {} snake_case__ : Union[str, Any] = trie_node[c] snake_case__ : Union[str, Any] = True snake_case__ : List[Any] = len(__magic_name__ ) # Dynamic programming method @functools.cache def is_breakable(__magic_name__ : int ) -> bool: if index == len_string: return True snake_case__ : Optional[Any] = trie for i in range(__magic_name__ , __magic_name__ ): snake_case__ : Tuple = trie_node.get(string[i] , __magic_name__ ) if trie_node is None: return False if trie_node.get(__magic_name__ , __magic_name__ ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
38
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin A_ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ : str = 250004 A_ : str = 250020 @require_sentencepiece @require_tokenizers class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MBartTokenizer lowerCamelCase__ = MBartTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing snake_case__ : Tuple = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self ): snake_case__ : Tuple = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) snake_case__ : int = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) snake_case__ : Optional[int] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) snake_case__ : Optional[int] = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) snake_case__ : Union[str, Any] = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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 __UpperCamelCase ( self ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return snake_case__ : Optional[int] = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = tempfile.mkdtemp() snake_case__ : int = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) snake_case__ : List[str] = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way snake_case__ : Tuple = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True snake_case__ : Any = tempfile.mkdtemp() snake_case__ : Optional[int] = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) snake_case__ : int = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way snake_case__ : List[Any] = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False snake_case__ : Dict = tempfile.mkdtemp() snake_case__ : Union[str, Any] = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way snake_case__ : Dict = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = '''facebook/mbart-large-en-ro''' lowerCamelCase__ = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] lowerCamelCase__ = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] lowerCamelCase__ = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def __UpperCamelCase ( cls ): snake_case__ : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) snake_case__ : Any = 1 return cls def __UpperCamelCase ( self ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 2_5_0_0_2_0 ) def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) snake_case__ : List[str] = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] snake_case__ : List[Any] = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = ["""this is gunna be a long sentence """ * 2_0] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = 1_0 snake_case__ : int = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [2_5_0_0_2_6, 2_5_0_0_0_1] ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = tempfile.mkdtemp() snake_case__ : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = MBartTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) snake_case__ : int = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) snake_case__ : List[str] = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 1_4) , batch.input_ids.shape ) self.assertEqual((2, 1_4) , batch.attention_mask.shape ) snake_case__ : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) snake_case__ : Optional[int] = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=1_0 , return_tensors="""pt""" ) snake_case__ : str = targets["""input_ids"""] snake_case__ : Optional[Any] = shift_tokens_right(__SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[6_2, 3_0_3_4, 2, 2_5_0_0_0_4]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 2_5_0_0_0_1, } , )
38
1
'''simple docstring''' import argparse import glob import logging import os from argparse import Namespace from importlib import import_module import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader, TensorDataset from utils_ner import TokenClassificationTask A_ : Optional[int] = logging.getLogger(__name__) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''token-classification''' def __init__( self , __SCREAMING_SNAKE_CASE ): if type(__SCREAMING_SNAKE_CASE ) == dict: snake_case__ : Optional[Any] = Namespace(**__SCREAMING_SNAKE_CASE ) snake_case__ : int = import_module("""tasks""" ) try: snake_case__ : Optional[int] = getattr(__SCREAMING_SNAKE_CASE , hparams.task_type ) snake_case__ : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f"Task {hparams.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. " f"Available tasks classes are: {TokenClassificationTask.__subclasses__()}" ) snake_case__ : Optional[int] = self.token_classification_task.get_labels(hparams.labels ) snake_case__ : Optional[int] = CrossEntropyLoss().ignore_index super().__init__(__SCREAMING_SNAKE_CASE , len(self.labels ) , self.mode ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): return self.model(**__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type != "distilbert": snake_case__ : Any = ( batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None ) # XLM and RoBERTa don"t use token_type_ids snake_case__ : Any = self(**__SCREAMING_SNAKE_CASE ) snake_case__ : int = outputs[0] # tensorboard_logs = {"loss": loss, "rate": self.lr_scheduler.get_last_lr()[-1]} return {"loss": loss} def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.hparams for mode in ["train", "dev", "test"]: snake_case__ : str = self._feature_file(__SCREAMING_SNAKE_CASE ) if os.path.exists(__SCREAMING_SNAKE_CASE ) and not args.overwrite_cache: logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = torch.load(__SCREAMING_SNAKE_CASE ) else: logger.info("""Creating features from dataset file at %s""" , args.data_dir ) snake_case__ : Optional[int] = self.token_classification_task.read_examples_from_file(args.data_dir , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = self.token_classification_task.convert_examples_to_features( __SCREAMING_SNAKE_CASE , self.labels , args.max_seq_length , self.tokenizer , cls_token_at_end=bool(self.config.model_type in ["""xlnet"""] ) , cls_token=self.tokenizer.cls_token , cls_token_segment_id=2 if self.config.model_type in ["""xlnet"""] else 0 , sep_token=self.tokenizer.sep_token , sep_token_extra=__SCREAMING_SNAKE_CASE , pad_on_left=bool(self.config.model_type in ["""xlnet"""] ) , pad_token=self.tokenizer.pad_token_id , pad_token_segment_id=self.tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info("""Saving features into cached file %s""" , __SCREAMING_SNAKE_CASE ) torch.save(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = False ): snake_case__ : Optional[int] = self._feature_file(__SCREAMING_SNAKE_CASE ) logger.info("""Loading features from cached file %s""" , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = torch.load(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) snake_case__ : int = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) if features[0].token_type_ids is not None: snake_case__ : List[str] = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) else: snake_case__ : Optional[Any] = torch.tensor([0 for f in features] , dtype=torch.long ) # HACK(we will not use this anymore soon) snake_case__ : Optional[Any] = torch.tensor([f.label_ids for f in features] , dtype=torch.long ) return DataLoader( TensorDataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) , batch_size=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """Compute validation""" "" snake_case__ : Optional[Any] = {"""input_ids""": batch[0], """attention_mask""": batch[1], """labels""": batch[3]} if self.config.model_type != "distilbert": snake_case__ : Tuple = ( batch[2] if self.config.model_type in ["""bert""", """xlnet"""] else None ) # XLM and RoBERTa don"t use token_type_ids snake_case__ : str = self(**__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ : Optional[Any] = outputs[:2] snake_case__ : Union[str, Any] = logits.detach().cpu().numpy() snake_case__ : Optional[int] = inputs["""labels"""].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = torch.stack([x["""val_loss"""] for x in outputs] ).mean() snake_case__ : Tuple = np.concatenate([x["""pred"""] for x in outputs] , axis=0 ) snake_case__ : List[Any] = np.argmax(__SCREAMING_SNAKE_CASE , axis=2 ) snake_case__ : Optional[int] = np.concatenate([x["""target"""] for x in outputs] , axis=0 ) snake_case__ : List[str] = dict(enumerate(self.labels ) ) snake_case__ : Any = [[] for _ in range(out_label_ids.shape[0] )] snake_case__ : Optional[int] = [[] for _ in range(out_label_ids.shape[0] )] for i in range(out_label_ids.shape[0] ): for j in range(out_label_ids.shape[1] ): if out_label_ids[i, j] != self.pad_token_label_id: out_label_list[i].append(label_map[out_label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) snake_case__ : int = { """val_loss""": val_loss_mean, """accuracy_score""": accuracy_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), """precision""": precision_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), """recall""": recall_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), """f1""": fa_score(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ), } snake_case__ : Any = dict(results.items() ) snake_case__ : Dict = results return ret, preds_list, out_label_list def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): # when stable snake_case__ , snake_case__ , snake_case__ : Any = self._eval_end(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = ret["""log"""] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): # updating to test_epoch_end instead of deprecated test_end snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = self._eval_end(__SCREAMING_SNAKE_CASE ) # Converting to the dict required by pl # https://github.com/PyTorchLightning/pytorch-lightning/blob/master/\ # pytorch_lightning/trainer/logging.py#L139 snake_case__ : Dict = ret["""log"""] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def __UpperCamelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Add NER specific options BaseTransformer.add_model_specific_args(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) parser.add_argument( """--task_type""" , default="""NER""" , type=__SCREAMING_SNAKE_CASE , help="""Task type to fine tune in training (e.g. NER, POS, etc)""" ) parser.add_argument( """--max_seq_length""" , default=1_2_8 , type=__SCREAMING_SNAKE_CASE , help=( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) , ) parser.add_argument( """--labels""" , default="""""" , type=__SCREAMING_SNAKE_CASE , help="""Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.""" , ) parser.add_argument( """--gpus""" , default=0 , type=__SCREAMING_SNAKE_CASE , help="""The number of GPUs allocated for this, it is by default 0 meaning none""" , ) parser.add_argument( """--overwrite_cache""" , action="""store_true""" , help="""Overwrite the cached training and evaluation sets""" ) return parser if __name__ == "__main__": A_ : Dict = argparse.ArgumentParser() add_generic_args(parser, os.getcwd()) A_ : int = NERTransformer.add_model_specific_args(parser, os.getcwd()) A_ : List[Any] = parser.parse_args() A_ : Union[str, Any] = NERTransformer(args) A_ : str = generic_train(model, args) if args.do_predict: # See https://github.com/huggingface/transformers/issues/3159 # pl use this default format to create a checkpoint: # https://github.com/PyTorchLightning/pytorch-lightning/blob/master\ # /pytorch_lightning/callbacks/model_checkpoint.py#L322 A_ : Union[str, Any] = sorted(glob.glob(os.path.join(args.output_dir, "checkpoint-epoch=*.ckpt"), recursive=True)) A_ : List[str] = model.load_from_checkpoint(checkpoints[-1]) trainer.test(model)
38
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : int = logging.get_logger(__name__) A_ : Dict = { "google/bit-50": "https://huggingface.co/google/bit-50/resolve/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''bit''' lowerCamelCase__ = ['''preactivation''', '''bottleneck'''] lowerCamelCase__ = ['''SAME''', '''VALID'''] def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , __SCREAMING_SNAKE_CASE=[3, 4, 6, 3] , __SCREAMING_SNAKE_CASE="preactivation" , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) if global_padding is not None: if global_padding.upper() in self.supported_padding: snake_case__ : Tuple = global_padding.upper() else: raise ValueError(f"Padding strategy {global_padding} not supported" ) snake_case__ : List[str] = num_channels snake_case__ : Tuple = embedding_size snake_case__ : str = hidden_sizes snake_case__ : Optional[Any] = depths snake_case__ : List[Any] = layer_type snake_case__ : Dict = hidden_act snake_case__ : Union[str, Any] = global_padding snake_case__ : List[str] = num_groups snake_case__ : str = drop_path_rate snake_case__ : List[Any] = embedding_dynamic_padding snake_case__ : List[str] = output_stride snake_case__ : Dict = width_factor snake_case__ : List[str] = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] snake_case__ , snake_case__ : Dict = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
38
1
'''simple docstring''' import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin A_ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = XLMProphetNetTokenizer lowerCamelCase__ = False lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing snake_case__ : List[str] = XLMProphetNetTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self ): snake_case__ : Optional[int] = """[PAD]""" snake_case__ : Dict = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """[PAD]""" ) self.assertEqual(vocab_keys[1] , """[CLS]""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , 1_0_1_2 ) def __UpperCamelCase ( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1_0_1_2 ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = XLMProphetNetTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) snake_case__ : Optional[int] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) snake_case__ : Tuple = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, -9, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, -9, 4] ] , ) snake_case__ : Optional[Any] = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """[UNK]""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """[UNK]""", """.""", ] , ) @cached_property def __UpperCamelCase ( self ): return XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased""" ) @slow def __UpperCamelCase ( self ): snake_case__ : Dict = """Hello World!""" snake_case__ : str = [3_5_3_8_9, 6_6_7_2, 4_9, 2] self.assertListEqual(__SCREAMING_SNAKE_CASE , self.big_tokenizer.encode(__SCREAMING_SNAKE_CASE ) ) @slow def __UpperCamelCase ( self ): # fmt: off snake_case__ : List[Any] = {"""input_ids""": [[1_1_0_7_3, 8_2_7_8_3, 1_8, 2_6, 8_2_7_8_3, 5_4_9, 5_1_5_4_0, 2_4_8, 1_7_2_0_9, 1_3_0_1, 2_1_7, 2_0, 2_1_5_1_8_6, 1_3_2_5, 1_4_7, 1_7_2_0_9, 1_3_0_1, 2_1_7, 2_0, 5_6_3_7_0, 5_3, 1_2_2_0_2_0, 2_0, 1_6_4_7_7, 2_7, 8_7_3_5_5, 4_5_4_8, 2_0, 4_7_2_8, 7_8_3_9_2, 1_7, 1_5_9_9_6_9, 1_8, 2_6, 2_4_4_9_1, 6_2_9, 1_5, 5_3_8, 2_2_7_0_4, 5_4_3_9, 1_5, 2_7_8_8, 2_4_4_9_1, 9_8_8_5, 1_5, 4_3_5_3_4, 6_0_5, 1_5, 8_1_4, 1_8_4_0_3, 3_3_2_0_0, 2_9, 1_5, 4_3_5_3_4, 2_4_4_5_8, 1_2_4_1_0, 1_1_1, 2_4_9_6_6, 8_3_6_6_9, 9_6_3_7, 1_4_4_0_6_8, 2_6, 8_5_0, 2_2_3_4_6, 2_7, 1_4_7, 2_4_9_6_6, 8_3_6_6_9, 8_3_4_9_0, 2_6, 3_9_1_1_3, 7_3_5, 2_7, 6_8_9, 6_5_6, 2_8_0_0, 1_3_3_9, 4_6_0_0, 5_3, 1_2_2_0_2_0, 1_1_5_7_8_5, 3_4, 8_1_6, 1_3_3_9, 4_6_8_8_7, 1_8, 1_4_7, 5_3_9_0_5, 1_9_5_1, 4_2_2_3_8, 4_1_1_7_0, 1_7_7_3_2, 8_3_4, 4_3_6, 1_5, 2_7_5_2_3, 9_8_7_3_3, 2_1_7, 1_4_7, 5_5_4_2, 4_9_8_1, 9_3_0, 1_7_3_4_7, 1_6, 2], [2_0_0_9_1, 6_2_9, 9_4, 8_2_7_8_6, 5_8, 4_9_0, 2_0, 1_5_2_8, 8_4, 5_3_9_0_5, 3_4_4, 8_0_5_9_2, 1_1_0_1_2_8, 1_8_8_2_2, 5_2_6_7, 1_3_0_6, 6_2, 1_5_2_5_3_7, 3_0_8, 7_9_9_7, 4_0_1, 1_2_4_4_2_7, 5_4_9, 3_5_4_4_2, 2_2_5, 1_0_9, 1_5_0_5_5, 2_5_7_4_8, 1_4_7, 7_1_1_9, 4_3_7_1_2, 3_4, 7_6_7, 1_3_5_3_6_6, 1_8, 1_6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_9_2, 6_3_7_8_4, 1_1_9_4_6_6, 1_7, 1_4_7_8_0_8, 8_8_2_1_4, 1_8, 6_5_6, 8_1, 3_2, 3_2_9_6, 1_0_2_8_0, 1_6, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__SCREAMING_SNAKE_CASE , model_name="""microsoft/xprophetnet-large-wiki100-cased""" , revision="""1acad1643ddd54a44df6a1b797ada8373685d90e""" , )
38
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() A_ : Optional[int] = logging.get_logger(__name__) def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : str=False ) -> Tuple: '''simple docstring''' snake_case__ : int = [] # fmt: off # stem: rename_keys.append(("""cls_token""", """vit.embeddings.cls_token""") ) rename_keys.append(("""pos_embed""", """vit.embeddings.position_embeddings""") ) rename_keys.append(("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias""") ) # backbone rename_keys.append(("""patch_embed.backbone.stem.conv.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.bias""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias""") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias") ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case__ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) # fmt: on return rename_keys def UpperCamelCase__ ( __magic_name__ : Tuple , __magic_name__ : int , __magic_name__ : Tuple=False ) -> str: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: snake_case__ : int = """""" else: snake_case__ : Dict = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case__ : int = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) snake_case__ : Union[str, Any] = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] snake_case__ : Optional[Any] = in_proj_bias[: config.hidden_size] snake_case__ : List[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case__ : List[Any] = in_proj_weight[ -config.hidden_size :, : ] snake_case__ : Optional[int] = in_proj_bias[-config.hidden_size :] def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> List[str]: '''simple docstring''' snake_case__ : str = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(__magic_name__ , __magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : str ) -> Union[str, Any]: '''simple docstring''' snake_case__ : List[str] = dct.pop(__magic_name__ ) snake_case__ : Dict = val def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : Optional[int] = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) return im @torch.no_grad() def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : int=False ) -> Optional[int]: '''simple docstring''' snake_case__ : int = BitConfig( global_padding="""same""" , layer_type="""bottleneck""" , depths=(3, 4, 9) , out_features=["""stage3"""] , embedding_dynamic_padding=__magic_name__ , ) snake_case__ : Optional[int] = ViTHybridConfig(backbone_config=__magic_name__ , image_size=3_84 , num_labels=10_00 ) snake_case__ : Union[str, Any] = False # load original model from timm snake_case__ : List[Any] = timm.create_model(__magic_name__ , pretrained=__magic_name__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case__ : Optional[int] = timm_model.state_dict() if base_model: remove_classification_head_(__magic_name__ ) snake_case__ : int = create_rename_keys(__magic_name__ , __magic_name__ ) for src, dest in rename_keys: rename_key(__magic_name__ , __magic_name__ , __magic_name__ ) read_in_q_k_v(__magic_name__ , __magic_name__ , __magic_name__ ) snake_case__ : str = """huggingface/label-files""" snake_case__ : Union[str, Any] = """imagenet-1k-id2label.json""" snake_case__ : Dict = json.load(open(hf_hub_download(__magic_name__ , __magic_name__ , repo_type="""dataset""" ) , """r""" ) ) snake_case__ : List[Any] = {int(__magic_name__ ): v for k, v in idalabel.items()} snake_case__ : int = idalabel snake_case__ : str = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": snake_case__ : str = ViTHybridModel(__magic_name__ ).eval() else: snake_case__ : Union[str, Any] = ViTHybridForImageClassification(__magic_name__ ).eval() model.load_state_dict(__magic_name__ ) # create image processor snake_case__ : Optional[Any] = create_transform(**resolve_data_config({} , model=__magic_name__ ) ) snake_case__ : Union[str, Any] = transform.transforms snake_case__ : Tuple = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } snake_case__ : Any = ViTHybridImageProcessor( do_resize=__magic_name__ , size={"""shortest_edge""": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=__magic_name__ , crop_size={"""height""": timm_transforms[1].size[0], """width""": timm_transforms[1].size[1]} , do_normalize=__magic_name__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) snake_case__ : Any = prepare_img() snake_case__ : int = transform(__magic_name__ ).unsqueeze(0 ) snake_case__ : List[str] = processor(__magic_name__ , return_tensors="""pt""" ).pixel_values # verify pixel values assert torch.allclose(__magic_name__ , __magic_name__ ) # verify logits with torch.no_grad(): snake_case__ : Optional[Any] = model(__magic_name__ ) snake_case__ : Union[str, Any] = outputs.logits print("""Predicted class:""" , logits.argmax(-1 ).item() ) if base_model: snake_case__ : Dict = timm_model.forward_features(__magic_name__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(__magic_name__ , outputs.pooler_output , atol=1E-3 ) else: snake_case__ : int = timm_model(__magic_name__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__magic_name__ , outputs.logits , atol=1E-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(__magic_name__ ) if push_to_hub: print(f"Pushing model and processor to the hub {vit_name}" ) model.push_to_hub(f"ybelkada/{vit_name}" ) processor.push_to_hub(f"ybelkada/{vit_name}" ) if __name__ == "__main__": A_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) A_ : Union[str, Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
38
1
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __snake_case ( unittest.TestCase , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : int = load_tool("""text-to-speech""" ) self.tool.setup() def __UpperCamelCase ( self ): # SpeechT5 isn't deterministic torch.manual_seed(0 ) snake_case__ : List[Any] = self.tool("""hey""" ) snake_case__ : List[str] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.000_5966_6688_3211_5829, -0.000_3657_6401_9079_5064, -0.0001_3439_5027_9988_3485] ) , ) ) def __UpperCamelCase ( self ): # SpeechT5 isn't deterministic torch.manual_seed(0 ) snake_case__ : Tuple = self.tool("""hey""" ) snake_case__ : Tuple = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.000_5966_6688_3211_5829, -0.000_3657_6401_9079_5064, -0.0001_3439_5027_9988_3485] ) , ) )
38
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = 42 class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("DownEncoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE=True , ): super().__init__() snake_case__ : str = layers_per_block snake_case__ : int = torch.nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : List[Any] = None snake_case__ : List[Any] = nn.ModuleList([] ) # down snake_case__ : Union[str, Any] = block_out_channels[0] for i, down_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = output_channel snake_case__ : Union[str, Any] = block_out_channels[i] snake_case__ : int = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : str = get_down_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) self.down_blocks.append(__SCREAMING_SNAKE_CASE ) # mid snake_case__ : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # out snake_case__ : Tuple = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : str = 2 * out_channels if double_z else out_channels snake_case__ : int = nn.Convad(block_out_channels[-1] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : Union[str, Any] = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = x snake_case__ : int = self.conv_in(__SCREAMING_SNAKE_CASE ) if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) # middle snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: for down_block in self.down_blocks: snake_case__ : Dict = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE ) else: # down for down_block in self.down_blocks: snake_case__ : List[str] = down_block(__SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = self.mid_block(__SCREAMING_SNAKE_CASE ) # post-process snake_case__ : Any = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : str = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("UpDecoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE="group" , ): super().__init__() snake_case__ : Any = layers_per_block snake_case__ : Optional[Any] = nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : Union[str, Any] = None snake_case__ : Dict = nn.ModuleList([] ) snake_case__ : Optional[int] = in_channels if norm_type == """spatial""" else None # mid snake_case__ : Tuple = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # up snake_case__ : List[Any] = list(reversed(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[Any] = reversed_block_out_channels[0] for i, up_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = output_channel snake_case__ : Optional[Any] = reversed_block_out_channels[i] snake_case__ : List[str] = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : int = get_up_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block + 1 , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , prev_output_channel=__SCREAMING_SNAKE_CASE , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , resnet_time_scale_shift=__SCREAMING_SNAKE_CASE , ) self.up_blocks.append(__SCREAMING_SNAKE_CASE ) snake_case__ : int = output_channel # out if norm_type == "spatial": snake_case__ : List[Any] = SpatialNorm(block_out_channels[0] , __SCREAMING_SNAKE_CASE ) else: snake_case__ : Any = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : Union[str, Any] = nn.Convad(block_out_channels[0] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : int = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): snake_case__ : Union[str, Any] = z snake_case__ : Any = self.conv_in(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle snake_case__ : int = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) snake_case__ : int = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : List[str] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : Dict = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : List[Any] = self.mid_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : Dict = up_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # post-process if latent_embeds is None: snake_case__ : Optional[Any] = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) else: snake_case__ : str = self.conv_norm_out(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="random" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True ): super().__init__() snake_case__ : int = n_e snake_case__ : Optional[int] = vq_embed_dim snake_case__ : int = beta snake_case__ : Optional[int] = legacy snake_case__ : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) snake_case__ : List[str] = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) snake_case__ : Optional[Any] = self.used.shape[0] snake_case__ : List[str] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": snake_case__ : Dict = self.re_embed snake_case__ : List[str] = self.re_embed + 1 print( f"Remapping {self.n_e} indices to {self.re_embed} indices. " f"Using {self.unknown_index} for unknown indices." ) else: snake_case__ : Union[str, Any] = n_e snake_case__ : str = sane_index_shape def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : Dict = inds.reshape(ishape[0] , -1 ) snake_case__ : Any = self.used.to(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = (inds[:, :, None] == used[None, None, ...]).long() snake_case__ : List[Any] = match.argmax(-1 ) snake_case__ : List[str] = match.sum(2 ) < 1 if self.unknown_index == "random": snake_case__ : List[str] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: snake_case__ : Optional[Any] = self.unknown_index return new.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : int = inds.reshape(ishape[0] , -1 ) snake_case__ : Optional[int] = self.used.to(__SCREAMING_SNAKE_CASE ) if self.re_embed > self.used.shape[0]: # extra token snake_case__ : List[Any] = 0 # simply set to zero snake_case__ : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __SCREAMING_SNAKE_CASE ) return back.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): # reshape z -> (batch, height, width, channel) and flatten snake_case__ : Any = z.permute(0 , 2 , 3 , 1 ).contiguous() snake_case__ : Optional[Any] = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z snake_case__ : Dict = torch.argmin(torch.cdist(__SCREAMING_SNAKE_CASE , self.embedding.weight ) , dim=1 ) snake_case__ : Union[str, Any] = self.embedding(__SCREAMING_SNAKE_CASE ).view(z.shape ) snake_case__ : List[str] = None snake_case__ : Union[str, Any] = None # compute loss for embedding if not self.legacy: snake_case__ : Tuple = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: snake_case__ : List[Any] = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients snake_case__ : Any = z + (z_q - z).detach() # reshape back to match original input shape snake_case__ : Union[str, Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: snake_case__ : List[Any] = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis snake_case__ : str = self.remap_to_used(__SCREAMING_SNAKE_CASE ) snake_case__ : str = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: snake_case__ : Tuple = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # shape specifying (batch, height, width, channel) if self.remap is not None: snake_case__ : List[Any] = indices.reshape(shape[0] , -1 ) # add batch axis snake_case__ : Optional[int] = self.unmap_to_all(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = indices.reshape(-1 ) # flatten again # get quantized latent vectors snake_case__ : int = self.embedding(__SCREAMING_SNAKE_CASE ) if shape is not None: snake_case__ : str = z_q.view(__SCREAMING_SNAKE_CASE ) # reshape back to match original input shape snake_case__ : str = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): snake_case__ : Tuple = parameters snake_case__ , snake_case__ : Any = torch.chunk(__SCREAMING_SNAKE_CASE , 2 , dim=1 ) snake_case__ : Union[str, Any] = torch.clamp(self.logvar , -30.0 , 20.0 ) snake_case__ : Optional[int] = deterministic snake_case__ : Optional[int] = torch.exp(0.5 * self.logvar ) snake_case__ : Any = torch.exp(self.logvar ) if self.deterministic: snake_case__ : List[str] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE = None ): # make sure sample is on the same device as the parameters and has same dtype snake_case__ : Dict = randn_tensor( self.mean.shape , generator=__SCREAMING_SNAKE_CASE , device=self.parameters.device , dtype=self.parameters.dtype ) snake_case__ : Optional[int] = self.mean + self.std * sample return x def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) snake_case__ : Any = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): return self.mean
38
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) A_ : List[str] = { "configuration_convbert": ["CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvBertConfig", "ConvBertOnnxConfig"], "tokenization_convbert": ["ConvBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : List[str] = ["ConvBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ "CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "ConvBertForMaskedLM", "ConvBertForMultipleChoice", "ConvBertForQuestionAnswering", "ConvBertForSequenceClassification", "ConvBertForTokenClassification", "ConvBertLayer", "ConvBertModel", "ConvBertPreTrainedModel", "load_tf_weights_in_convbert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Any = [ "TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFConvBertForMaskedLM", "TFConvBertForMultipleChoice", "TFConvBertForQuestionAnswering", "TFConvBertForSequenceClassification", "TFConvBertForTokenClassification", "TFConvBertLayer", "TFConvBertModel", "TFConvBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig from .tokenization_convbert import ConvBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_convbert_fast import ConvBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convbert import ( CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertLayer, ConvBertModel, ConvBertPreTrainedModel, load_tf_weights_in_convbert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convbert import ( TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFConvBertForMaskedLM, TFConvBertForMultipleChoice, TFConvBertForQuestionAnswering, TFConvBertForSequenceClassification, TFConvBertForTokenClassification, TFConvBertLayer, TFConvBertModel, TFConvBertPreTrainedModel, ) else: import sys A_ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
38
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1_6 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=[0, 1, 2, 3] , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_7 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=[1, 3_8_4, 2_4, 2_4] , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , ): snake_case__ : str = parent snake_case__ : Union[str, Any] = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : Optional[int] = patch_size snake_case__ : List[str] = num_channels snake_case__ : Any = is_training snake_case__ : int = use_labels snake_case__ : str = hidden_size snake_case__ : Tuple = num_hidden_layers snake_case__ : str = backbone_out_indices snake_case__ : List[Any] = num_attention_heads snake_case__ : Dict = intermediate_size snake_case__ : Optional[Any] = hidden_act snake_case__ : str = hidden_dropout_prob snake_case__ : int = attention_probs_dropout_prob snake_case__ : Dict = initializer_range snake_case__ : Optional[int] = num_labels snake_case__ : str = backbone_featmap_shape snake_case__ : List[Any] = scope snake_case__ : Optional[Any] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) snake_case__ : List[Any] = (image_size // patch_size) ** 2 snake_case__ : Union[str, Any] = num_patches + 1 def __UpperCamelCase ( self ): snake_case__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : str = None if self.use_labels: snake_case__ : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): snake_case__ : Any = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [9_6, 1_9_2, 3_8_4, 7_6_8], """num_groups""": 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , 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=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=__SCREAMING_SNAKE_CASE , backbone_featmap_shape=self.backbone_featmap_shape , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = DPTModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Union[str, Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = self.num_labels snake_case__ : str = DPTForDepthEstimation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Optional[Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = self.num_labels snake_case__ : Dict = DPTForSemanticSegmentation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : str = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () lowerCamelCase__ = ( { '''depth-estimation''': DPTForDepthEstimation, '''feature-extraction''': DPTModel, '''image-segmentation''': DPTForSemanticSegmentation, } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : List[Any] = DPTModelTester(self ) snake_case__ : Any = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""DPT does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Tuple = model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : str = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : List[str] = [*signature.parameters.keys()] snake_case__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : int = True if model_class in get_values(__SCREAMING_SNAKE_CASE ): continue snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.train() snake_case__ : Optional[Any] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCamelCase ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Union[str, Any] = False snake_case__ : str = True if model_class in get_values(__SCREAMING_SNAKE_CASE ) or not model_class.supports_gradient_checkpointing: continue snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.train() snake_case__ : List[str] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCamelCase ( self ): snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : str = _config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: snake_case__ : Any = model_class(config=__SCREAMING_SNAKE_CASE ) # Skip the check for the backbone snake_case__ : str = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": snake_case__ : Optional[int] = [f"{name}.{key}" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCamelCase ( self ): pass @slow def __UpperCamelCase ( self ): for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: snake_case__ : List[str] = DPTModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Dict = """add""" with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = DPTForDepthEstimation(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( ) -> Dict: '''simple docstring''' snake_case__ : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision @slow class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Dict = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" ) snake_case__ : Union[str, Any] = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = prepare_img() snake_case__ : Optional[int] = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): snake_case__ : Dict = model(**__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = outputs.predicted_depth # verify the predicted depth snake_case__ : Any = torch.Size((1, 3_8_4, 3_8_4) ) self.assertEqual(predicted_depth.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0 , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
1
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = 42 lowerCamelCase__ = 42 lowerCamelCase__ = None class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = 2 @register_to_config def __init__( self , __SCREAMING_SNAKE_CASE = 0.02 , __SCREAMING_SNAKE_CASE = 1_0_0 , __SCREAMING_SNAKE_CASE = 1.007 , __SCREAMING_SNAKE_CASE = 8_0 , __SCREAMING_SNAKE_CASE = 0.05 , __SCREAMING_SNAKE_CASE = 5_0 , ): # standard deviation of the initial noise distribution snake_case__ : int = sigma_max # setable values snake_case__ : int = None snake_case__ : np.IntTensor = None snake_case__ : torch.FloatTensor = None # sigma(t_i) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): return sample def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): snake_case__ : Tuple = num_inference_steps snake_case__ : List[Any] = np.arange(0 , self.num_inference_steps )[::-1].copy() snake_case__ : Any = torch.from_numpy(__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] snake_case__ : List[Any] = torch.tensor(__SCREAMING_SNAKE_CASE , dtype=torch.floataa , device=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None ): if self.config.s_min <= sigma <= self.config.s_max: snake_case__ : Any = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: snake_case__ : Union[str, Any] = 0 # sample eps ~ N(0, S_noise^2 * I) snake_case__ : Optional[int] = self.config.s_noise * randn_tensor(sample.shape , generator=__SCREAMING_SNAKE_CASE ).to(sample.device ) snake_case__ : List[Any] = sigma + gamma * sigma snake_case__ : Optional[int] = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = True , ): snake_case__ : Union[str, Any] = sample_hat + sigma_hat * model_output snake_case__ : List[Any] = (sample_hat - pred_original_sample) / sigma_hat snake_case__ : Optional[int] = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=__SCREAMING_SNAKE_CASE , derivative=__SCREAMING_SNAKE_CASE , pred_original_sample=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = True , ): snake_case__ : List[str] = sample_prev + sigma_prev * model_output snake_case__ : Tuple = (sample_prev - pred_original_sample) / sigma_prev snake_case__ : List[str] = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=__SCREAMING_SNAKE_CASE , derivative=__SCREAMING_SNAKE_CASE , pred_original_sample=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): raise NotImplementedError()
38
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Dict: '''simple docstring''' snake_case__ : int = botoa.client("""iam""" ) snake_case__ : Union[str, Any] = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=__magic_name__ , AssumeRolePolicyDocument=json.dumps(__magic_name__ , indent=2 ) ) snake_case__ : Dict = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=__magic_name__ , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(__magic_name__ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def UpperCamelCase__ ( __magic_name__ : Any ) -> Tuple: '''simple docstring''' snake_case__ : List[str] = botoa.client("""iam""" ) return iam_client.get_role(RoleName=__magic_name__ )["Role"]["Arn"] def UpperCamelCase__ ( ) -> Tuple: '''simple docstring''' snake_case__ : Union[str, Any] = _ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , __magic_name__ , ) snake_case__ : List[Any] = None if credentials_configuration == 0: snake_case__ : Dict = _ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) snake_case__ : List[str] = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) snake_case__ : List[str] = _ask_field("""AWS Access Key ID: """ ) snake_case__ : int = aws_access_key_id snake_case__ : Optional[Any] = _ask_field("""AWS Secret Access Key: """ ) snake_case__ : List[str] = aws_secret_access_key snake_case__ : Tuple = _ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) snake_case__ : Optional[int] = aws_region snake_case__ : int = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , __magic_name__ , ) if role_management == 0: snake_case__ : Optional[Any] = _ask_field("""Enter your IAM role name: """ ) else: snake_case__ : Optional[int] = """accelerate_sagemaker_execution_role""" print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(__magic_name__ ) snake_case__ : Dict = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Any = None if is_custom_docker_image: snake_case__ : str = _ask_field("""Enter your Docker image: """ , lambda __magic_name__ : str(__magic_name__ ).lower() ) snake_case__ : Tuple = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : List[Any] = None if is_sagemaker_inputs_enabled: snake_case__ : str = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Optional[int] = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Optional[Any] = None if is_sagemaker_metrics_enabled: snake_case__ : List[Any] = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Tuple = _ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) snake_case__ : Any = {} snake_case__ : List[Any] = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_dynamo: snake_case__ : str = """dynamo_""" snake_case__ : Tuple = _ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) snake_case__ : List[str] = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_custom_options: snake_case__ : str = _ask_options( """Which mode do you want to use?""" , __magic_name__ , lambda __magic_name__ : TORCH_DYNAMO_MODES[int(__magic_name__ )] , default="""default""" , ) snake_case__ : Union[str, Any] = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : str = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Dict = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: snake_case__ : List[str] = _ask_options( __magic_name__ , __magic_name__ , lambda __magic_name__ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(__magic_name__ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" snake_case__ : Optional[int] = _ask_field(__magic_name__ , lambda __magic_name__ : str(__magic_name__ ).lower() , default="""ml.p3.2xlarge""" ) snake_case__ : Dict = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): snake_case__ : Optional[Any] = _ask_field( """How many machines do you want use? [1]: """ , __magic_name__ , default=1 , ) snake_case__ : Union[str, Any] = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=__magic_name__ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=__magic_name__ , use_cpu=__magic_name__ , dynamo_config=__magic_name__ , eca_instance_type=__magic_name__ , profile=__magic_name__ , region=__magic_name__ , iam_role_name=__magic_name__ , mixed_precision=__magic_name__ , num_machines=__magic_name__ , sagemaker_inputs_file=__magic_name__ , sagemaker_metrics_file=__magic_name__ , )
38
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) def UpperCamelCase__ ( *__magic_name__ : Dict , **__magic_name__ : int ) -> Optional[int]: '''simple docstring''' requires_backends(__magic_name__ , ["""torch"""] ) def UpperCamelCase__ ( *__magic_name__ : Union[str, Any] , **__magic_name__ : Dict ) -> Optional[Any]: '''simple docstring''' requires_backends(__magic_name__ , ["""torch"""] ) def UpperCamelCase__ ( *__magic_name__ : Dict , **__magic_name__ : str ) -> str: '''simple docstring''' requires_backends(__magic_name__ , ["""torch"""] ) def UpperCamelCase__ ( *__magic_name__ : Union[str, Any] , **__magic_name__ : Any ) -> Optional[Any]: '''simple docstring''' requires_backends(__magic_name__ , ["""torch"""] ) def UpperCamelCase__ ( *__magic_name__ : int , **__magic_name__ : Union[str, Any] ) -> Any: '''simple docstring''' requires_backends(__magic_name__ , ["""torch"""] ) def UpperCamelCase__ ( *__magic_name__ : Optional[Any] , **__magic_name__ : Dict ) -> List[str]: '''simple docstring''' requires_backends(__magic_name__ , ["""torch"""] ) def UpperCamelCase__ ( *__magic_name__ : Tuple , **__magic_name__ : str ) -> Dict: '''simple docstring''' requires_backends(__magic_name__ , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) class __snake_case ( metaclass=__SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = ['''torch'''] def __init__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(self , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] ) @classmethod def __UpperCamelCase ( cls , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): requires_backends(cls , ["""torch"""] )
38
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def UpperCamelCase__ ( __magic_name__ : str = "laptop" ) -> DataFrame: '''simple docstring''' snake_case__ : Union[str, Any] = f"https://www.amazon.in/laptop/s?k={product}" snake_case__ : List[str] = { """User-Agent""": """Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36""", """Accept-Language""": """en-US, en;q=0.5""", } snake_case__ : int = BeautifulSoup(requests.get(__magic_name__ , headers=__magic_name__ ).text ) # Initialize a Pandas dataframe with the column titles snake_case__ : Optional[Any] = DataFrame( columns=[ """Product Title""", """Product Link""", """Current Price of the product""", """Product Rating""", """MRP of the product""", """Discount""", ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( """div""" , attrs={"""class""": """s-result-item""", """data-component-type""": """s-search-result"""} , ) , soup.find_all("""div""" , attrs={"""class""": """a-row a-size-base a-color-base"""} ) , ): try: snake_case__ : Optional[int] = item.ha.text snake_case__ : Any = """https://www.amazon.in/""" + item.ha.a["""href"""] snake_case__ : List[str] = item.find("""span""" , attrs={"""class""": """a-offscreen"""} ).text try: snake_case__ : Dict = item.find("""span""" , attrs={"""class""": """a-icon-alt"""} ).text except AttributeError: snake_case__ : Optional[int] = """Not available""" try: snake_case__ : Tuple = ( """₹""" + item.find( """span""" , attrs={"""class""": """a-price a-text-price"""} ).text.split("""₹""" )[1] ) except AttributeError: snake_case__ : Optional[Any] = """""" try: snake_case__ : str = float( ( ( float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) - float(product_price.strip("""₹""" ).replace(""",""" , """""" ) ) ) / float(product_mrp.strip("""₹""" ).replace(""",""" , """""" ) ) ) * 1_00 ) except ValueError: snake_case__ : List[Any] = float("""nan""" ) except AttributeError: pass snake_case__ : str = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] snake_case__ : List[Any] = """ """ snake_case__ : Union[str, Any] = """ """ data_frame.index += 1 return data_frame if __name__ == "__main__": A_ : int = "headphones" get_amazon_product_data(product).to_csv(F'Amazon Product Data for {product}.csv')
38
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self ): snake_case__ : Dict = TFXLMRobertaModel.from_pretrained("""jplu/tf-xlm-roberta-base""" ) snake_case__ : Union[str, Any] = { """input_ids""": tf.convert_to_tensor([[0, 2_6_4_6, 1_0_2_6_9, 8_3, 9_9_9_4_2, 2]] , dtype=tf.intaa ), # "My dog is cute" """attention_mask""": tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ), } snake_case__ : Optional[Any] = model(__SCREAMING_SNAKE_CASE )["""last_hidden_state"""] snake_case__ : Optional[Any] = tf.TensorShape((1, 6, 7_6_8) ) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) # compare the actual values for a slice. snake_case__ : str = tf.convert_to_tensor( [ [ [0.068_1762, 0.1089_4451, 0.0677_2504], [-0.0642_3668, 0.0236_6615, 0.0432_9344], [-0.0605_7295, 0.0997_4135, -0.0007_0584], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
38
'''simple docstring''' import itertools import json import os import unittest from transformers import AddedToken, LongformerTokenizer, LongformerTokenizerFast from transformers.models.longformer.tokenization_longformer import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = LongformerTokenizer lowerCamelCase__ = True lowerCamelCase__ = LongformerTokenizerFast lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case__ : Union[str, Any] = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] snake_case__ : Optional[int] = dict(zip(__SCREAMING_SNAKE_CASE , range(len(__SCREAMING_SNAKE_CASE ) ) ) ) snake_case__ : int = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] snake_case__ : Any = {"""unk_token""": """<unk>"""} snake_case__ : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) snake_case__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__SCREAMING_SNAKE_CASE ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__SCREAMING_SNAKE_CASE ) ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , **__SCREAMING_SNAKE_CASE ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : str = """lower newer""" snake_case__ : Dict = """lower newer""" return input_text, output_text def __UpperCamelCase ( self ): snake_case__ : int = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case__ : Tuple = """lower newer""" snake_case__ : Optional[Any] = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] snake_case__ : Tuple = tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) # , add_prefix_space=True) self.assertListEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokens + [tokenizer.unk_token] snake_case__ : List[Any] = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Tuple = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [0, 3_1_4_1_4, 2_3_2, 3_2_8, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) , [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] , ) @slow def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.tokenizer_class.from_pretrained("""allenai/longformer-base-4096""" ) snake_case__ : int = tokenizer.encode("""sequence builders""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer.encode( """sequence builders""" , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.get_tokenizer() snake_case__ : int = """Encode this sequence.""" snake_case__ : Union[str, Any] = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments snake_case__ : Optional[int] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) snake_case__ : List[str] = tokenizer.encode(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Testing spaces after special tokens snake_case__ : List[str] = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(__SCREAMING_SNAKE_CASE , lstrip=__SCREAMING_SNAKE_CASE , rstrip=__SCREAMING_SNAKE_CASE )} ) # mask token has a left space snake_case__ : Dict = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) snake_case__ : str = """Encode <mask> sequence""" snake_case__ : Tuple = """Encode <mask>sequence""" snake_case__ : Union[str, Any] = tokenizer.encode(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = encoded.index(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer.encode(__SCREAMING_SNAKE_CASE ) snake_case__ : str = encoded.index(__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = """A, <mask> AllenNLP sentence.""" snake_case__ : str = tokenizer_r.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = tokenizer_p.encode_plus(__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) snake_case__ : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) snake_case__ : Dict = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( __SCREAMING_SNAKE_CASE , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def __UpperCamelCase ( self ): for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): snake_case__ : Any = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) snake_case__ : List[str] = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state["""add_prefix_space"""] , __SCREAMING_SNAKE_CASE ) self.assertEqual(post_processor_state["""trim_offsets"""] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` and # `trim_offsets` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : Union[str, Any] = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` snake_case__ : Any = f"{text_of_1_token} {text_of_1_token}" snake_case__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ) + 1, len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : str = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Tuple = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__SCREAMING_SNAKE_CASE ), len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Optional[Any] = f" {text}" # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) snake_case__ : Dict = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ) + 1, 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : Any = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , ) snake_case__ : List[Any] = self.rust_tokenizer_class.from_pretrained( __SCREAMING_SNAKE_CASE , use_fast=__SCREAMING_SNAKE_CASE , add_prefix_space=__SCREAMING_SNAKE_CASE , trim_offsets=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = tokenizer_r(__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__SCREAMING_SNAKE_CASE )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__SCREAMING_SNAKE_CASE ), 1 + len(__SCREAMING_SNAKE_CASE ) + 1 + len(__SCREAMING_SNAKE_CASE )) , )
38
1
'''simple docstring''' import pytest from datasets.utils.sharding import _distribute_shards, _number_of_shards_in_gen_kwargs, _split_gen_kwargs @pytest.mark.parametrize( """kwargs, expected""" , [ ({"""num_shards""": 0, """max_num_jobs""": 1}, []), ({"""num_shards""": 10, """max_num_jobs""": 1}, [range(10 )]), ({"""num_shards""": 10, """max_num_jobs""": 10}, [range(__magic_name__ , i + 1 ) for i in range(10 )]), ({"""num_shards""": 1, """max_num_jobs""": 10}, [range(1 )]), ({"""num_shards""": 10, """max_num_jobs""": 3}, [range(0 , 4 ), range(4 , 7 ), range(7 , 10 )]), ({"""num_shards""": 3, """max_num_jobs""": 10}, [range(0 , 1 ), range(1 , 2 ), range(2 , 3 )]), ] , ) def UpperCamelCase__ ( __magic_name__ : Dict , __magic_name__ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' snake_case__ : List[str] = _distribute_shards(**__magic_name__ ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, max_num_jobs, expected""" , [ ({"""foo""": 0}, 10, [{"""foo""": 0}]), ({"""shards""": [0, 1, 2, 3]}, 1, [{"""shards""": [0, 1, 2, 3]}]), ({"""shards""": [0, 1, 2, 3]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}, {"""shards""": [2]}, {"""shards""": [3]}]), ({"""shards""": [0, 1]}, 4, [{"""shards""": [0]}, {"""shards""": [1]}]), ({"""shards""": [0, 1, 2, 3]}, 2, [{"""shards""": [0, 1]}, {"""shards""": [2, 3]}]), ] , ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Optional[int] , __magic_name__ : List[Any] ) -> int: '''simple docstring''' snake_case__ : Dict = _split_gen_kwargs(__magic_name__ , __magic_name__ ) assert out == expected @pytest.mark.parametrize( """gen_kwargs, expected""" , [ ({"""foo""": 0}, 1), ({"""shards""": [0]}, 1), ({"""shards""": [0, 1, 2, 3]}, 4), ({"""shards""": [0, 1, 2, 3], """foo""": 0}, 4), ({"""shards""": [0, 1, 2, 3], """other""": (0, 1)}, 4), ({"""shards""": [0, 1, 2, 3], """shards2""": [0, 1]}, RuntimeError), ] , ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Tuple ) -> List[str]: '''simple docstring''' if expected is RuntimeError: with pytest.raises(__magic_name__ ): _number_of_shards_in_gen_kwargs(__magic_name__ ) else: snake_case__ : Any = _number_of_shards_in_gen_kwargs(__magic_name__ ) assert out == expected
38
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : int = logging.get_logger(__name__) A_ : Any = { "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''resnet''' lowerCamelCase__ = ['''basic''', '''bottleneck'''] def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , __SCREAMING_SNAKE_CASE=[3, 4, 6, 3] , __SCREAMING_SNAKE_CASE="bottleneck" , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) snake_case__ : List[Any] = num_channels snake_case__ : str = embedding_size snake_case__ : List[Any] = hidden_sizes snake_case__ : Dict = depths snake_case__ : List[Any] = layer_type snake_case__ : int = hidden_act snake_case__ : Union[str, Any] = downsample_in_first_stage snake_case__ : Dict = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] snake_case__ , snake_case__ : Any = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names ) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = version.parse('''1.11''' ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __UpperCamelCase ( self ): return 1e-3
38
1
'''simple docstring''' from __future__ import annotations A_ : Tuple = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = graph # mapping node to its parent in resulting breadth first tree snake_case__ : dict[str, str | None] = {} snake_case__ : Dict = source_vertex def __UpperCamelCase ( self ): snake_case__ : Optional[int] = {self.source_vertex} snake_case__ : int = None snake_case__ : Any = [self.source_vertex] # first in first out queue while queue: snake_case__ : List[Any] = queue.pop(0 ) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = vertex queue.append(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): if target_vertex == self.source_vertex: return self.source_vertex snake_case__ : Union[str, Any] = self.parent.get(__SCREAMING_SNAKE_CASE ) if target_vertex_parent is None: snake_case__ : Optional[Any] = ( f"No path from vertex: {self.source_vertex} to vertex: {target_vertex}" ) raise ValueError(__SCREAMING_SNAKE_CASE ) return self.shortest_path(__SCREAMING_SNAKE_CASE ) + f"->{target_vertex}" if __name__ == "__main__": A_ : Optional[int] = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
38
'''simple docstring''' # limitations under the License. # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401 from .utils import deprecate deprecate( "pipelines_utils", "0.22.0", "Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.", standard_warn=False, stacklevel=3, )
38
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. snake_case__ : int = [[1, 2, 4], [1, 2, 3, 4]] snake_case__ : Any = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) self.assertTrue(isinstance(dc.token_ids , __SCREAMING_SNAKE_CASE ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __UpperCamelCase ( self ): # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). snake_case__ : Union[str, Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) # fails here def __UpperCamelCase ( self ): snake_case__ : List[str] = [[1, 2, 3], [1, 2, 4]] snake_case__ : Optional[int] = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ , snake_case__ : Any = dc.update(1 ) snake_case__ : Any = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : Tuple = dc.update(2 ) snake_case__ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = dc.update(3 ) snake_case__ : List[str] = stepped is True and completed is True and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] snake_case__ : int = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ , snake_case__ : str = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : Dict = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
38
'''simple docstring''' import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self ): snake_case__ : str = [] def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_init_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_train_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_train_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_epoch_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_epoch_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_step_begin""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_step_end""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_evaluate""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_predict""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_save""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_log""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): self.events.append("""on_prediction_step""" ) @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Tuple = tempfile.mkdtemp() def __UpperCamelCase ( self ): shutil.rmtree(self.output_dir ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=False , **__SCREAMING_SNAKE_CASE ): # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. snake_case__ : List[Any] = RegressionDataset(length=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionDataset(length=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionModelConfig(a=__SCREAMING_SNAKE_CASE , b=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = RegressionPreTrainedModel(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = TrainingArguments(self.output_dir , disable_tqdm=__SCREAMING_SNAKE_CASE , report_to=[] , **__SCREAMING_SNAKE_CASE ) return Trainer( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , train_dataset=__SCREAMING_SNAKE_CASE , eval_dataset=__SCREAMING_SNAKE_CASE , callbacks=__SCREAMING_SNAKE_CASE , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , len(__SCREAMING_SNAKE_CASE ) ) # Order doesn't matter snake_case__ : Tuple = sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : cb.__name__ if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else cb.__class__.__name__ ) snake_case__ : List[str] = sorted(__SCREAMING_SNAKE_CASE , key=lambda __SCREAMING_SNAKE_CASE : cb.__name__ if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else cb.__class__.__name__ ) for cba, cba in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(__SCREAMING_SNAKE_CASE , cba.__class__ ) elif not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) and isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): self.assertEqual(cba.__class__ , __SCREAMING_SNAKE_CASE ) else: self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = ["""on_init_end""", """on_train_begin"""] snake_case__ : Union[str, Any] = 0 snake_case__ : Dict = len(trainer.get_eval_dataloader() ) snake_case__ : Any = ["""on_prediction_step"""] * len(trainer.get_eval_dataloader() ) + ["""on_log""", """on_evaluate"""] for _ in range(trainer.state.num_train_epochs ): expected_events.append("""on_epoch_begin""" ) for _ in range(__SCREAMING_SNAKE_CASE ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append("""on_log""" ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append("""on_save""" ) expected_events.append("""on_epoch_end""" ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __UpperCamelCase ( self ): snake_case__ : Any = self.get_trainer() snake_case__ : str = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # Callbacks passed at init are added to the default callbacks snake_case__ : List[str] = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback snake_case__ : Optional[Any] = self.get_trainer(disable_tqdm=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = DEFAULT_CALLBACKS.copy() + [ProgressCallback] snake_case__ : int = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.remove(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = self.get_trainer() snake_case__ : List[str] = trainer.pop_callback(__SCREAMING_SNAKE_CASE ) self.assertEqual(cb.__class__ , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) trainer.add_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.insert(0 , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) # We can also add, pop, or remove by instance snake_case__ : List[Any] = self.get_trainer() snake_case__ : List[str] = trainer.callback_handler.callbacks[0] trainer.remove_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.remove(__SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = self.get_trainer() snake_case__ : Any = trainer.callback_handler.callbacks[0] snake_case__ : Optional[Any] = trainer.pop_callback(__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) trainer.add_callback(__SCREAMING_SNAKE_CASE ) expected_callbacks.insert(0 , __SCREAMING_SNAKE_CASE ) self.check_callbacks_equality(trainer.callback_handler.callbacks , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action="""ignore""" , category=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # Independent log/save/eval snake_case__ : Dict = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() snake_case__ : int = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Any = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Tuple = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy="""steps""" ) trainer.train() snake_case__ : str = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Tuple = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy="""epoch""" ) trainer.train() snake_case__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # A bit of everything snake_case__ : Dict = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=1_0 , eval_steps=5 , evaluation_strategy="""steps""" , ) trainer.train() snake_case__ : Tuple = trainer.callback_handler.callbacks[-2].events self.assertEqual(__SCREAMING_SNAKE_CASE , self.get_expected_events(__SCREAMING_SNAKE_CASE ) ) # warning should be emitted for duplicated callbacks with patch("""transformers.trainer_callback.logger.warning""" ) as warn_mock: snake_case__ : List[str] = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(__SCREAMING_SNAKE_CASE ) in warn_mock.call_args[0][0]
38
1
'''simple docstring''' import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin from .feature_extraction_wavaveca import WavaVecaFeatureExtractor from .tokenization_wavaveca import WavaVecaCTCTokenizer class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''Wav2Vec2FeatureExtractor''' lowerCamelCase__ = '''AutoTokenizer''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = self.feature_extractor snake_case__ : Optional[Any] = False @classmethod def __UpperCamelCase ( cls , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): try: return super().from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) except OSError: warnings.warn( f"Loading a tokenizer inside {cls.__name__} from a config that does not" """ include a `tokenizer_class` attribute is deprecated and will be """ """removed in v5. Please add `'tokenizer_class': 'Wav2Vec2CTCTokenizer'`""" """ attribute to either your `config.json` or `tokenizer_config.json` """ """file to suppress this warning: """ , __SCREAMING_SNAKE_CASE , ) snake_case__ : List[str] = WavaVecaFeatureExtractor.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = WavaVecaCTCTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) return cls(feature_extractor=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE ) def __call__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) snake_case__ : Optional[Any] = kwargs.pop("""raw_speech""" ) else: snake_case__ : Union[str, Any] = kwargs.pop("""audio""" , __SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = kwargs.pop("""sampling_rate""" , __SCREAMING_SNAKE_CASE ) snake_case__ : Dict = kwargs.pop("""text""" , __SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: snake_case__ : Optional[Any] = args[0] snake_case__ : Dict = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: snake_case__ : Optional[int] = self.feature_extractor(__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text is not None: snake_case__ : Any = self.tokenizer(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if text is None: return inputs elif audio is None: return encodings else: snake_case__ : List[Any] = encodings["""input_ids"""] return inputs def __UpperCamelCase ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): # For backward compatibility if self._in_target_context_manager: return self.current_processor.pad(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Any = kwargs.pop("""input_features""" , __SCREAMING_SNAKE_CASE ) snake_case__ : str = kwargs.pop("""labels""" , __SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) > 0: snake_case__ : Dict = args[0] snake_case__ : int = args[1:] if input_features is not None: snake_case__ : Any = self.feature_extractor.pad(__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if labels is not None: snake_case__ : List[Any] = self.tokenizer.pad(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) if labels is None: return input_features elif input_features is None: return labels else: snake_case__ : Tuple = labels["""input_ids"""] return input_features def __UpperCamelCase ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @contextmanager def __UpperCamelCase ( self ): warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) snake_case__ : List[str] = True snake_case__ : Any = self.tokenizer yield snake_case__ : str = self.feature_extractor snake_case__ : str = False
38
'''simple docstring''' import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision 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 DPTImageProcessor class __snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=1_8 , __SCREAMING_SNAKE_CASE=3_0 , __SCREAMING_SNAKE_CASE=4_0_0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ): snake_case__ : Any = size if size is not None else {"""height""": 1_8, """width""": 1_8} snake_case__ : List[Any] = parent snake_case__ : int = batch_size snake_case__ : List[Any] = num_channels snake_case__ : str = image_size snake_case__ : Union[str, Any] = min_resolution snake_case__ : List[Any] = max_resolution snake_case__ : Tuple = do_resize snake_case__ : int = size snake_case__ : Tuple = do_normalize snake_case__ : Dict = image_mean snake_case__ : Union[str, Any] = image_std def __UpperCamelCase ( self ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = DPTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self ): snake_case__ : str = DPTImageProcessingTester(self ) @property def __UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_std""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """size""" ) ) def __UpperCamelCase ( self ): snake_case__ : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 1_8, """width""": 1_8} ) snake_case__ : List[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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input snake_case__ : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case__ : List[str] = image_processing(__SCREAMING_SNAKE_CASE , 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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case__ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input snake_case__ : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case__ : Any = image_processing(__SCREAMING_SNAKE_CASE , 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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case__ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input snake_case__ : List[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 snake_case__ : List[str] = image_processing(__SCREAMING_SNAKE_CASE , 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"""], ) , )
38
1
'''simple docstring''' A_ : Tuple = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" A_ : int = [{"type": "code", "content": INSTALL_CONTENT}] A_ : Optional[int] = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
38
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig 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 TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Dict = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """embed_dim""" ) ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """num_heads""" ) ) class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=[1_6, 4_8, 9_6] , __SCREAMING_SNAKE_CASE=[1, 3, 6] , __SCREAMING_SNAKE_CASE=[1, 2, 1_0] , __SCREAMING_SNAKE_CASE=[7, 3, 3] , __SCREAMING_SNAKE_CASE=[4, 2, 2] , __SCREAMING_SNAKE_CASE=[2, 1, 1] , __SCREAMING_SNAKE_CASE=[2, 2, 2] , __SCREAMING_SNAKE_CASE=[False, False, True] , __SCREAMING_SNAKE_CASE=[0.0, 0.0, 0.0] , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=2 , ): snake_case__ : List[str] = parent snake_case__ : Tuple = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : List[Any] = patch_sizes snake_case__ : Optional[int] = patch_stride snake_case__ : Optional[Any] = patch_padding snake_case__ : Any = is_training snake_case__ : int = use_labels snake_case__ : Dict = num_labels snake_case__ : Optional[Any] = num_channels snake_case__ : Optional[Any] = embed_dim snake_case__ : Optional[int] = num_heads snake_case__ : Optional[int] = stride_kv snake_case__ : int = depth snake_case__ : Optional[Any] = cls_token snake_case__ : List[Any] = attention_drop_rate snake_case__ : Union[str, Any] = initializer_range snake_case__ : List[Any] = layer_norm_eps def __UpperCamelCase ( self ): snake_case__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[Any] = None if self.use_labels: # create a random int32 tensor of given shape snake_case__ : List[str] = ids_tensor([self.batch_size] , self.num_labels ) snake_case__ : List[str] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = TFCvtModel(config=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = model(__SCREAMING_SNAKE_CASE , training=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = (self.image_size, self.image_size) snake_case__ , snake_case__ : str = image_size[0], image_size[1] for i in range(len(self.depth ) ): snake_case__ : Any = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) snake_case__ : Optional[int] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = self.num_labels snake_case__ : str = TFCvtForImageClassification(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , training=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Union[str, Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () lowerCamelCase__ = ( {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification} if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = TFCvtModelTester(self ) snake_case__ : Any = TFCvtConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason="""Cvt does not output attentions""" ) def __UpperCamelCase ( self ): pass @unittest.skip(reason="""Cvt does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass @unittest.skip(reason="""Cvt does not support input and output embeddings""" ) def __UpperCamelCase ( self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) def __UpperCamelCase ( self ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def __UpperCamelCase ( self ): super().test_keras_fit() @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""" ) def __UpperCamelCase ( self ): snake_case__ : List[str] = tf.keras.mixed_precision.Policy("""mixed_float16""" ) tf.keras.mixed_precision.set_global_policy(__SCREAMING_SNAKE_CASE ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("""float32""" ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Optional[Any] = [*signature.parameters.keys()] snake_case__ : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): def check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[int] = outputs.hidden_states snake_case__ : Tuple = len(self.model_tester.depth ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : List[Any] = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[str] = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def __UpperCamelCase ( self ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : str = TFCvtModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class __snake_case ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCamelCase ( self ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) snake_case__ : Union[str, Any] = self.default_image_processor snake_case__ : int = prepare_img() snake_case__ : Dict = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) # forward pass snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE ) # verify the logits snake_case__ : str = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : int = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
1
'''simple docstring''' import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_3 , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=9_9 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_7 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=5_0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , ): snake_case__ : List[str] = parent snake_case__ : str = batch_size snake_case__ : Dict = seq_length snake_case__ : int = is_training snake_case__ : Optional[Any] = use_input_mask snake_case__ : Tuple = vocab_size snake_case__ : Tuple = hidden_size snake_case__ : List[str] = num_hidden_layers snake_case__ : List[str] = num_attention_heads snake_case__ : List[str] = intermediate_size snake_case__ : Optional[Any] = hidden_act snake_case__ : Union[str, Any] = hidden_dropout_prob snake_case__ : Dict = attention_probs_dropout_prob snake_case__ : Optional[int] = max_position_embeddings snake_case__ : List[Any] = initializer_range snake_case__ : str = use_labels snake_case__ : Tuple = scope def __UpperCamelCase ( self ): snake_case__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case__ : int = None if self.use_input_mask: snake_case__ : str = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: snake_case__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case__ : Any = self.get_config() return config, input_ids, input_mask, token_labels def __UpperCamelCase ( self ): return BertGenerationConfig( 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 , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self ): ( ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ) : List[str] = self.prepare_config_and_inputs() snake_case__ : str = True snake_case__ : Tuple = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) snake_case__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ): snake_case__ : Union[str, Any] = BertGenerationEncoder(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : str = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ): snake_case__ : str = True snake_case__ : List[Any] = BertGenerationEncoder(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Dict = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , encoder_attention_mask=__SCREAMING_SNAKE_CASE , ) snake_case__ : List[Any] = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ): snake_case__ : List[Any] = True snake_case__ : Optional[int] = True snake_case__ : int = BertGenerationDecoder(config=__SCREAMING_SNAKE_CASE ).to(__SCREAMING_SNAKE_CASE ).eval() # first forward pass snake_case__ : int = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , encoder_attention_mask=__SCREAMING_SNAKE_CASE , use_cache=__SCREAMING_SNAKE_CASE , ) snake_case__ : List[Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids snake_case__ : int = ids_tensor((self.batch_size, 3) , config.vocab_size ) snake_case__ : int = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and snake_case__ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case__ : Optional[Any] = torch.cat([input_mask, next_mask] , dim=-1 ) snake_case__ : Any = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , encoder_attention_mask=__SCREAMING_SNAKE_CASE , output_hidden_states=__SCREAMING_SNAKE_CASE , )["""hidden_states"""][0] snake_case__ : List[str] = model( __SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , encoder_hidden_states=__SCREAMING_SNAKE_CASE , encoder_attention_mask=__SCREAMING_SNAKE_CASE , past_key_values=__SCREAMING_SNAKE_CASE , output_hidden_states=__SCREAMING_SNAKE_CASE , )["""hidden_states"""][0] # select random slice snake_case__ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() snake_case__ : int = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1e-3 ) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , ): snake_case__ : List[str] = BertGenerationDecoder(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Dict = model(__SCREAMING_SNAKE_CASE , attention_mask=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ , snake_case__ , snake_case__ : int = self.prepare_config_and_inputs() snake_case__ : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () lowerCamelCase__ = (BertGenerationDecoder,) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': BertGenerationEncoder, '''text-generation''': BertGenerationDecoder} if is_torch_available() else {} ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = BertGenerationEncoderTester(self ) snake_case__ : List[str] = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.run_common_tests() def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ , snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs() snake_case__ : List[Any] = """bert""" self.model_tester.create_and_check_model(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # This regression test was failing with PyTorch < 1.3 ( ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ( snake_case__ ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_decoder() snake_case__ : Tuple = None self.model_tester.create_and_check_model_as_decoder( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) def __UpperCamelCase ( self ): snake_case__ : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*__SCREAMING_SNAKE_CASE ) @slow def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) snake_case__ : List[Any] = torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]] ) with torch.no_grad(): snake_case__ : List[Any] = model(__SCREAMING_SNAKE_CASE )[0] snake_case__ : str = torch.Size([1, 8, 1_0_2_4] ) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) ) @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self ): snake_case__ : List[Any] = BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) snake_case__ : Tuple = torch.tensor([[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_2_6, 3_8_9_9, 2_0_0_3, 1_0_1_4_0, 1_0_2]] ) with torch.no_grad(): snake_case__ : Optional[Any] = model(__SCREAMING_SNAKE_CASE )[0] snake_case__ : List[Any] = torch.Size([1, 8, 5_0_3_5_8] ) self.assertEqual(output.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. snake_case__ : int = [[1, 2, 4], [1, 2, 3, 4]] snake_case__ : Any = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) self.assertTrue(isinstance(dc.token_ids , __SCREAMING_SNAKE_CASE ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def __UpperCamelCase ( self ): # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). snake_case__ : Union[str, Any] = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__SCREAMING_SNAKE_CASE ): DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) # fails here def __UpperCamelCase ( self ): snake_case__ : List[str] = [[1, 2, 3], [1, 2, 4]] snake_case__ : Optional[int] = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ , snake_case__ : Any = dc.update(1 ) snake_case__ : Any = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : Tuple = dc.update(2 ) snake_case__ : Tuple = stepped is True and completed is False and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = dc.update(3 ) snake_case__ : List[str] = stepped is True and completed is True and reset is False self.assertTrue(__SCREAMING_SNAKE_CASE ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] snake_case__ : int = DisjunctiveConstraint(__SCREAMING_SNAKE_CASE ) snake_case__ , snake_case__ , snake_case__ : str = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : str = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) snake_case__ , snake_case__ , snake_case__ : List[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) snake_case__ , snake_case__ , snake_case__ : Dict = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
38
1
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig 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 TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Dict = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """embed_dim""" ) ) self.parent.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """num_heads""" ) ) class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=[1_6, 4_8, 9_6] , __SCREAMING_SNAKE_CASE=[1, 3, 6] , __SCREAMING_SNAKE_CASE=[1, 2, 1_0] , __SCREAMING_SNAKE_CASE=[7, 3, 3] , __SCREAMING_SNAKE_CASE=[4, 2, 2] , __SCREAMING_SNAKE_CASE=[2, 1, 1] , __SCREAMING_SNAKE_CASE=[2, 2, 2] , __SCREAMING_SNAKE_CASE=[False, False, True] , __SCREAMING_SNAKE_CASE=[0.0, 0.0, 0.0] , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=2 , ): snake_case__ : List[str] = parent snake_case__ : Tuple = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : List[Any] = patch_sizes snake_case__ : Optional[int] = patch_stride snake_case__ : Optional[Any] = patch_padding snake_case__ : Any = is_training snake_case__ : int = use_labels snake_case__ : Dict = num_labels snake_case__ : Optional[Any] = num_channels snake_case__ : Optional[Any] = embed_dim snake_case__ : Optional[int] = num_heads snake_case__ : Optional[int] = stride_kv snake_case__ : int = depth snake_case__ : Optional[Any] = cls_token snake_case__ : List[Any] = attention_drop_rate snake_case__ : Union[str, Any] = initializer_range snake_case__ : List[Any] = layer_norm_eps def __UpperCamelCase ( self ): snake_case__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[Any] = None if self.use_labels: # create a random int32 tensor of given shape snake_case__ : List[str] = ids_tensor([self.batch_size] , self.num_labels ) snake_case__ : List[str] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = TFCvtModel(config=__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = model(__SCREAMING_SNAKE_CASE , training=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = (self.image_size, self.image_size) snake_case__ , snake_case__ : str = image_size[0], image_size[1] for i in range(len(self.depth ) ): snake_case__ : Any = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) snake_case__ : Optional[int] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = self.num_labels snake_case__ : str = TFCvtForImageClassification(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE , training=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Union[str, Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () lowerCamelCase__ = ( {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification} if is_tf_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = TFCvtModelTester(self ) snake_case__ : Any = TFCvtConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason="""Cvt does not output attentions""" ) def __UpperCamelCase ( self ): pass @unittest.skip(reason="""Cvt does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass @unittest.skip(reason="""Cvt does not support input and output embeddings""" ) def __UpperCamelCase ( self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) def __UpperCamelCase ( self ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("""GPU""" ) ) == 0 , reason="""TF does not support backprop for grouped convolutions on CPU.""" , ) @slow def __UpperCamelCase ( self ): super().test_keras_fit() @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""" ) def __UpperCamelCase ( self ): snake_case__ : List[str] = tf.keras.mixed_precision.Policy("""mixed_float16""" ) tf.keras.mixed_precision.set_global_policy(__SCREAMING_SNAKE_CASE ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("""float32""" ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : str = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Optional[Any] = [*signature.parameters.keys()] snake_case__ : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): def check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[int] = outputs.hidden_states snake_case__ : Tuple = len(self.model_tester.depth ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : List[Any] = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[str] = True check_hidden_states_output(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) @slow def __UpperCamelCase ( self ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : str = TFCvtModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class __snake_case ( unittest.TestCase ): '''simple docstring''' @cached_property def __UpperCamelCase ( self ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) snake_case__ : Union[str, Any] = self.default_image_processor snake_case__ : int = prepare_img() snake_case__ : Dict = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""tf""" ) # forward pass snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE ) # verify the logits snake_case__ : str = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : int = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
'''simple docstring''' import warnings from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Optional[int] = logging.get_logger(__name__) A_ : Tuple = { "nvidia/segformer-b0-finetuned-ade-512-512": ( "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json" ), # See all SegFormer models at https://huggingface.co/models?filter=segformer } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''segformer''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=[2, 2, 2, 2] , __SCREAMING_SNAKE_CASE=[8, 4, 2, 1] , __SCREAMING_SNAKE_CASE=[3_2, 6_4, 1_6_0, 2_5_6] , __SCREAMING_SNAKE_CASE=[7, 3, 3, 3] , __SCREAMING_SNAKE_CASE=[4, 2, 2, 2] , __SCREAMING_SNAKE_CASE=[1, 2, 5, 8] , __SCREAMING_SNAKE_CASE=[4, 4, 4, 4] , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1e-6 , __SCREAMING_SNAKE_CASE=2_5_6 , __SCREAMING_SNAKE_CASE=2_5_5 , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False: warnings.warn( """Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be""" """ removed, as the behaviour will default to that of reshape_last_stage = True.""" , __SCREAMING_SNAKE_CASE , ) snake_case__ : Dict = num_channels snake_case__ : Optional[Any] = num_encoder_blocks snake_case__ : Any = depths snake_case__ : Optional[int] = sr_ratios snake_case__ : Tuple = hidden_sizes snake_case__ : List[str] = patch_sizes snake_case__ : str = strides snake_case__ : Optional[int] = mlp_ratios snake_case__ : Optional[Any] = num_attention_heads snake_case__ : Dict = hidden_act snake_case__ : Optional[int] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : List[Any] = classifier_dropout_prob snake_case__ : int = initializer_range snake_case__ : List[str] = drop_path_rate snake_case__ : int = layer_norm_eps snake_case__ : List[Any] = decoder_hidden_size snake_case__ : List[Any] = kwargs.get("""reshape_last_stage""" , __SCREAMING_SNAKE_CASE ) snake_case__ : Dict = semantic_loss_ignore_index class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = version.parse('''1.11''' ) @property def __UpperCamelCase ( self ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def __UpperCamelCase ( self ): return 1e-4 @property def __UpperCamelCase ( self ): return 1_2
38
1
'''simple docstring''' import unittest import numpy as np from transformers.file_utils import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision 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 DPTImageProcessor class __snake_case ( unittest.TestCase ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=1_8 , __SCREAMING_SNAKE_CASE=3_0 , __SCREAMING_SNAKE_CASE=4_0_0 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , __SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ): snake_case__ : Any = size if size is not None else {"""height""": 1_8, """width""": 1_8} snake_case__ : List[Any] = parent snake_case__ : int = batch_size snake_case__ : List[Any] = num_channels snake_case__ : str = image_size snake_case__ : Union[str, Any] = min_resolution snake_case__ : List[Any] = max_resolution snake_case__ : Tuple = do_resize snake_case__ : int = size snake_case__ : Tuple = do_normalize snake_case__ : Dict = image_mean snake_case__ : Union[str, Any] = image_std def __UpperCamelCase ( self ): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = DPTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self ): snake_case__ : str = DPTImageProcessingTester(self ) @property def __UpperCamelCase ( self ): return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_mean""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """image_std""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_normalize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """do_resize""" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , """size""" ) ) def __UpperCamelCase ( self ): snake_case__ : Any = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""height""": 1_8, """width""": 1_8} ) snake_case__ : List[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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , Image.Image ) # Test not batched input snake_case__ : Optional[int] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case__ : List[str] = image_processing(__SCREAMING_SNAKE_CASE , 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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case__ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , np.ndarray ) # Test not batched input snake_case__ : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["""height"""], self.image_processor_tester.size["""width"""], ) , ) # Test batched snake_case__ : Any = image_processing(__SCREAMING_SNAKE_CASE , 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 __UpperCamelCase ( self ): # Initialize image_processing snake_case__ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case__ : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__SCREAMING_SNAKE_CASE , torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE , torch.Tensor ) # Test not batched input snake_case__ : List[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 snake_case__ : List[str] = image_processing(__SCREAMING_SNAKE_CASE , 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"""], ) , )
38
'''simple docstring''' import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : List[Any]=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : str = None if token is not None: snake_case__ : str = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : List[Any] = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" snake_case__ : str = requests.get(__magic_name__ , headers=__magic_name__ ).json() snake_case__ : str = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) snake_case__ : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(__magic_name__ ): snake_case__ : Tuple = requests.get(url + f"&page={i + 2}" , headers=__magic_name__ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any]=None ) -> List[str]: '''simple docstring''' snake_case__ : Optional[Any] = None if token is not None: snake_case__ : Any = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : Dict = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" snake_case__ : Union[str, Any] = requests.get(__magic_name__ , headers=__magic_name__ ).json() snake_case__ : Dict = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) snake_case__ : List[Any] = math.ceil((result["""total_count"""] - 1_00) / 1_00 ) for i in range(__magic_name__ ): snake_case__ : Dict = requests.get(url + f"&page={i + 2}" , headers=__magic_name__ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} def UpperCamelCase__ ( __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , __magic_name__ : Dict ) -> Dict: '''simple docstring''' snake_case__ : Optional[Any] = None if token is not None: snake_case__ : Dict = {"""Accept""": """application/vnd.github+json""", """Authorization""": f"Bearer {token}"} snake_case__ : str = requests.get(__magic_name__ , headers=__magic_name__ , allow_redirects=__magic_name__ ) snake_case__ : Any = result.headers["""Location"""] snake_case__ : Tuple = requests.get(__magic_name__ , allow_redirects=__magic_name__ ) snake_case__ : int = os.path.join(__magic_name__ , f"{artifact_name}.zip" ) with open(__magic_name__ , """wb""" ) as fp: fp.write(response.content ) def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : str=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Any = [] snake_case__ : Union[str, Any] = [] snake_case__ : Any = None with zipfile.ZipFile(__magic_name__ ) as z: for filename in z.namelist(): if not os.path.isdir(__magic_name__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(__magic_name__ ) as f: for line in f: snake_case__ : Any = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs snake_case__ : str = line[: line.index(""": """ )] snake_case__ : Optional[int] = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed snake_case__ : Dict = line[len("""FAILED """ ) :] failed_tests.append(__magic_name__ ) elif filename == "job_name.txt": snake_case__ : Optional[Any] = line if len(__magic_name__ ) != len(__magic_name__ ): raise ValueError( f"`errors` and `failed_tests` should have the same number of elements. Got {len(__magic_name__ )} for `errors` " f"and {len(__magic_name__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" """ problem.""" ) snake_case__ : Optional[Any] = None if job_name and job_links: snake_case__ : Optional[Any] = job_links.get(__magic_name__ , __magic_name__ ) # A list with elements of the form (line of error, error, failed test) snake_case__ : List[Any] = [x + [y] + [job_link] for x, y in zip(__magic_name__ , __magic_name__ )] return result def UpperCamelCase__ ( __magic_name__ : int , __magic_name__ : Union[str, Any]=None ) -> Union[str, Any]: '''simple docstring''' snake_case__ : str = [] snake_case__ : Dict = [os.path.join(__magic_name__ , __magic_name__ ) for p in os.listdir(__magic_name__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(__magic_name__ , job_links=__magic_name__ ) ) return errors def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : str=None ) -> List[Any]: '''simple docstring''' snake_case__ : Any = Counter() counter.update([x[1] for x in logs] ) snake_case__ : Dict = counter.most_common() snake_case__ : Any = {} for error, count in counts: if error_filter is None or error not in error_filter: snake_case__ : int = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} snake_case__ : Union[str, Any] = dict(sorted(r.items() , key=lambda __magic_name__ : item[1]["count"] , reverse=__magic_name__ ) ) return r def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> List[Any]: '''simple docstring''' snake_case__ : str = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): snake_case__ : Tuple = test.split("""/""" )[2] else: snake_case__ : Any = None return test def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : Union[str, Any]=None ) -> List[str]: '''simple docstring''' snake_case__ : List[str] = [(x[0], x[1], get_model(x[2] )) for x in logs] snake_case__ : List[Any] = [x for x in logs if x[2] is not None] snake_case__ : Any = {x[2] for x in logs} snake_case__ : Optional[Any] = {} for test in tests: snake_case__ : str = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) snake_case__ : Optional[int] = counter.most_common() snake_case__ : Optional[int] = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} snake_case__ : int = sum(error_counts.values() ) if n_errors > 0: snake_case__ : str = {"""count""": n_errors, """errors""": error_counts} snake_case__ : Union[str, Any] = dict(sorted(r.items() , key=lambda __magic_name__ : item[1]["count"] , reverse=__magic_name__ ) ) return r def UpperCamelCase__ ( __magic_name__ : int ) -> Optional[int]: '''simple docstring''' snake_case__ : Optional[Any] = """| no. | error | status |""" snake_case__ : int = """|-:|:-|:-|""" snake_case__ : int = [header, sep] for error in reduced_by_error: snake_case__ : Union[str, Any] = reduced_by_error[error]["""count"""] snake_case__ : Dict = f"| {count} | {error[:1_00]} | |" lines.append(__magic_name__ ) return "\n".join(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> List[Any]: '''simple docstring''' snake_case__ : List[Any] = """| model | no. of errors | major error | count |""" snake_case__ : Optional[int] = """|-:|-:|-:|-:|""" snake_case__ : Dict = [header, sep] for model in reduced_by_model: snake_case__ : Tuple = reduced_by_model[model]["""count"""] snake_case__ , snake_case__ : Tuple = list(reduced_by_model[model]["""errors"""].items() )[0] snake_case__ : Optional[int] = f"| {model} | {count} | {error[:60]} | {_count} |" lines.append(__magic_name__ ) return "\n".join(__magic_name__ ) if __name__ == "__main__": A_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") A_ : int = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) A_ : Optional[int] = get_job_links(args.workflow_run_id, token=args.token) A_ : Optional[Any] = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: A_ : int = k.find(" / ") A_ : List[Any] = k[index + len(" / ") :] A_ : List[str] = v with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) A_ : int = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) A_ : str = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error A_ : List[str] = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors A_ : Any = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) A_ : Any = reduce_by_error(errors) A_ : Union[str, Any] = reduce_by_model(errors) A_ : Any = make_github_table(reduced_by_error) A_ : Optional[Any] = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: fp.write(sa) with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: fp.write(sa)
38
1
'''simple docstring''' import math def UpperCamelCase__ ( __magic_name__ : int ) -> int: '''simple docstring''' if not isinstance(__magic_name__ , __magic_name__ ): snake_case__ : Union[str, Any] = f"Input value of [number={number}] must be an integer" raise TypeError(__magic_name__ ) if number < 1: snake_case__ : Optional[int] = f"Input value of [number={number}] must be > 0" raise ValueError(__magic_name__ ) elif number == 1: return 3 elif number == 2: return 5 else: snake_case__ : Optional[int] = int(math.log(number // 3 , 2 ) ) + 2 snake_case__ : str = [3, 5] snake_case__ : List[Any] = 2 snake_case__ : Optional[Any] = 3 for block in range(1 , __magic_name__ ): for _ in range(__magic_name__ ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(11): A_ : Optional[int] = 0 try: A_ : Dict = proth(number) except ValueError: print(F'ValueError: there is no {number}th Proth number') continue print(F'The {number}th Proth number: {value}')
38
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version A_ : Tuple = get_logger(__name__) class __snake_case : '''simple docstring''' lowerCamelCase__ = '''dummy_data''' lowerCamelCase__ = '''datasets''' lowerCamelCase__ = False def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , ): snake_case__ : List[Any] = 0 snake_case__ : Union[str, Any] = dataset_name snake_case__ : Optional[int] = cache_dir snake_case__ : Union[str, Any] = use_local_dummy_data snake_case__ : int = config # download_callbacks take a single url as input snake_case__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root snake_case__ : Union[str, Any] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general snake_case__ : Union[str, Any] = str(__SCREAMING_SNAKE_CASE ) # to be downloaded snake_case__ : List[str] = None snake_case__ : List[str] = None @property def __UpperCamelCase ( self ): if self._dummy_file is None: snake_case__ : List[str] = self.download_dummy_data() return self._dummy_file @property def __UpperCamelCase ( self ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("""dummy""" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("""dummy""" , self.version_name ) @property def __UpperCamelCase ( self ): return os.path.join(self.dummy_data_folder , """dummy_data.zip""" ) def __UpperCamelCase ( self ): snake_case__ : Optional[Any] = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) snake_case__ : Optional[int] = cached_path( __SCREAMING_SNAKE_CASE , cache_dir=self.cache_dir , extract_compressed_file=__SCREAMING_SNAKE_CASE , force_extract=__SCREAMING_SNAKE_CASE ) return os.path.join(__SCREAMING_SNAKE_CASE , self.dummy_file_name ) @property def __UpperCamelCase ( self ): return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __UpperCamelCase ( self ): if self._bucket_url is None: snake_case__ : List[str] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , """/""" ) ) return self._bucket_url @property def __UpperCamelCase ( self ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , """/""" ).split("""/""" )[:-1] ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): if self.load_existing_dummy_data: # dummy data is downloaded and tested snake_case__ : List[Any] = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned snake_case__ : List[Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return self.create_dummy_data_dict(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) elif isinstance(__SCREAMING_SNAKE_CASE , (list, tuple) ): return self.create_dummy_data_list(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: return self.create_dummy_data_single(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): return self.download_and_extract(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return self.download_and_extract(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): return path def __UpperCamelCase ( self ): return {} def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for single_url in single_urls: download_callback(__SCREAMING_SNAKE_CASE ) else: snake_case__ : List[str] = single_urls download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = [os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(Path(__SCREAMING_SNAKE_CASE ).name ) ) for x in single_urls] else: snake_case__ : List[Any] = single_urls snake_case__ : Tuple = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(Path(__SCREAMING_SNAKE_CASE ).name ) ) snake_case__ : Optional[int] = value # make sure that values are unique if all(isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique snake_case__ : List[Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one snake_case__ : Tuple = all(bool(re.findall("""[0-9]{3,}-of-[0-9]{3,}""" , __SCREAMING_SNAKE_CASE ) ) for url in data_url ) snake_case__ : List[Any] = all( url.startswith("""https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed""" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): snake_case__ : List[str] = [data_url[0]] * len(__SCREAMING_SNAKE_CASE ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case__ : List[Any] = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(single_url.split("""/""" )[-1] ) ) dummy_data_list.append(__SCREAMING_SNAKE_CASE ) return dummy_data_list def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): for download_callback in self.download_callbacks: download_callback(__SCREAMING_SNAKE_CASE ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus snake_case__ : Any = os.path.join(__SCREAMING_SNAKE_CASE , urllib.parse.quote_plus(data_url.split("""/""" )[-1] ) ) if os.path.exists(__SCREAMING_SNAKE_CASE ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): def _iter_archive_members(__SCREAMING_SNAKE_CASE ): # this preserves the order of the members inside the ZIP archive snake_case__ : List[str] = Path(self.dummy_file ).parent snake_case__ : Dict = path.relative_to(__SCREAMING_SNAKE_CASE ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: snake_case__ : Optional[int] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = Path(__SCREAMING_SNAKE_CASE ) snake_case__ : int = _iter_archive_members(__SCREAMING_SNAKE_CASE ) if self.use_local_dummy_data else path.rglob("""*""" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((""".""", """__""") ): yield file_path.relative_to(__SCREAMING_SNAKE_CASE ).as_posix(), file_path.open("""rb""" ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): if not isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[int] = [paths] for path in paths: if os.path.isfile(__SCREAMING_SNAKE_CASE ): if os.path.basename(__SCREAMING_SNAKE_CASE ).startswith((""".""", """__""") ): return yield path else: for dirpath, dirnames, filenames in os.walk(__SCREAMING_SNAKE_CASE ): if os.path.basename(__SCREAMING_SNAKE_CASE ).startswith((""".""", """__""") ): continue dirnames.sort() for filename in sorted(__SCREAMING_SNAKE_CASE ): if filename.startswith((""".""", """__""") ): continue yield os.path.join(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE )
38
1
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = 42 class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("DownEncoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE=True , ): super().__init__() snake_case__ : str = layers_per_block snake_case__ : int = torch.nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : List[Any] = None snake_case__ : List[Any] = nn.ModuleList([] ) # down snake_case__ : Union[str, Any] = block_out_channels[0] for i, down_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = output_channel snake_case__ : Union[str, Any] = block_out_channels[i] snake_case__ : int = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : str = get_down_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) self.down_blocks.append(__SCREAMING_SNAKE_CASE ) # mid snake_case__ : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # out snake_case__ : Tuple = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : str = 2 * out_channels if double_z else out_channels snake_case__ : int = nn.Convad(block_out_channels[-1] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : Union[str, Any] = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = x snake_case__ : int = self.conv_in(__SCREAMING_SNAKE_CASE ) if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) # middle snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: for down_block in self.down_blocks: snake_case__ : Dict = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE ) else: # down for down_block in self.down_blocks: snake_case__ : List[str] = down_block(__SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = self.mid_block(__SCREAMING_SNAKE_CASE ) # post-process snake_case__ : Any = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : str = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("UpDecoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE="group" , ): super().__init__() snake_case__ : Any = layers_per_block snake_case__ : Optional[Any] = nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : Union[str, Any] = None snake_case__ : Dict = nn.ModuleList([] ) snake_case__ : Optional[int] = in_channels if norm_type == """spatial""" else None # mid snake_case__ : Tuple = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # up snake_case__ : List[Any] = list(reversed(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[Any] = reversed_block_out_channels[0] for i, up_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = output_channel snake_case__ : Optional[Any] = reversed_block_out_channels[i] snake_case__ : List[str] = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : int = get_up_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block + 1 , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , prev_output_channel=__SCREAMING_SNAKE_CASE , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , resnet_time_scale_shift=__SCREAMING_SNAKE_CASE , ) self.up_blocks.append(__SCREAMING_SNAKE_CASE ) snake_case__ : int = output_channel # out if norm_type == "spatial": snake_case__ : List[Any] = SpatialNorm(block_out_channels[0] , __SCREAMING_SNAKE_CASE ) else: snake_case__ : Any = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : Union[str, Any] = nn.Convad(block_out_channels[0] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : int = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): snake_case__ : Union[str, Any] = z snake_case__ : Any = self.conv_in(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle snake_case__ : int = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) snake_case__ : int = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : List[str] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : Dict = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : List[Any] = self.mid_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : Dict = up_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # post-process if latent_embeds is None: snake_case__ : Optional[Any] = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) else: snake_case__ : str = self.conv_norm_out(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="random" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True ): super().__init__() snake_case__ : int = n_e snake_case__ : Optional[int] = vq_embed_dim snake_case__ : int = beta snake_case__ : Optional[int] = legacy snake_case__ : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) snake_case__ : List[str] = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) snake_case__ : Optional[Any] = self.used.shape[0] snake_case__ : List[str] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": snake_case__ : Dict = self.re_embed snake_case__ : List[str] = self.re_embed + 1 print( f"Remapping {self.n_e} indices to {self.re_embed} indices. " f"Using {self.unknown_index} for unknown indices." ) else: snake_case__ : Union[str, Any] = n_e snake_case__ : str = sane_index_shape def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : Dict = inds.reshape(ishape[0] , -1 ) snake_case__ : Any = self.used.to(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = (inds[:, :, None] == used[None, None, ...]).long() snake_case__ : List[Any] = match.argmax(-1 ) snake_case__ : List[str] = match.sum(2 ) < 1 if self.unknown_index == "random": snake_case__ : List[str] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: snake_case__ : Optional[Any] = self.unknown_index return new.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : int = inds.reshape(ishape[0] , -1 ) snake_case__ : Optional[int] = self.used.to(__SCREAMING_SNAKE_CASE ) if self.re_embed > self.used.shape[0]: # extra token snake_case__ : List[Any] = 0 # simply set to zero snake_case__ : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __SCREAMING_SNAKE_CASE ) return back.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): # reshape z -> (batch, height, width, channel) and flatten snake_case__ : Any = z.permute(0 , 2 , 3 , 1 ).contiguous() snake_case__ : Optional[Any] = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z snake_case__ : Dict = torch.argmin(torch.cdist(__SCREAMING_SNAKE_CASE , self.embedding.weight ) , dim=1 ) snake_case__ : Union[str, Any] = self.embedding(__SCREAMING_SNAKE_CASE ).view(z.shape ) snake_case__ : List[str] = None snake_case__ : Union[str, Any] = None # compute loss for embedding if not self.legacy: snake_case__ : Tuple = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: snake_case__ : List[Any] = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients snake_case__ : Any = z + (z_q - z).detach() # reshape back to match original input shape snake_case__ : Union[str, Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: snake_case__ : List[Any] = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis snake_case__ : str = self.remap_to_used(__SCREAMING_SNAKE_CASE ) snake_case__ : str = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: snake_case__ : Tuple = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # shape specifying (batch, height, width, channel) if self.remap is not None: snake_case__ : List[Any] = indices.reshape(shape[0] , -1 ) # add batch axis snake_case__ : Optional[int] = self.unmap_to_all(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = indices.reshape(-1 ) # flatten again # get quantized latent vectors snake_case__ : int = self.embedding(__SCREAMING_SNAKE_CASE ) if shape is not None: snake_case__ : str = z_q.view(__SCREAMING_SNAKE_CASE ) # reshape back to match original input shape snake_case__ : str = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): snake_case__ : Tuple = parameters snake_case__ , snake_case__ : Any = torch.chunk(__SCREAMING_SNAKE_CASE , 2 , dim=1 ) snake_case__ : Union[str, Any] = torch.clamp(self.logvar , -30.0 , 20.0 ) snake_case__ : Optional[int] = deterministic snake_case__ : Optional[int] = torch.exp(0.5 * self.logvar ) snake_case__ : Any = torch.exp(self.logvar ) if self.deterministic: snake_case__ : List[str] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE = None ): # make sure sample is on the same device as the parameters and has same dtype snake_case__ : Dict = randn_tensor( self.mean.shape , generator=__SCREAMING_SNAKE_CASE , device=self.parameters.device , dtype=self.parameters.dtype ) snake_case__ : Optional[int] = self.mean + self.std * sample return x def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) snake_case__ : Any = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): return self.mean
38
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = IFImgaImgSuperResolutionPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def __UpperCamelCase ( self ): return self._get_superresolution_dummy_components() def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): snake_case__ : List[Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case__ : Tuple = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = floats_tensor((1, 3, 1_6, 1_6) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : int = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __UpperCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __UpperCamelCase ( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __UpperCamelCase ( self ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def __UpperCamelCase ( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __UpperCamelCase ( self ): self._test_save_load_local() def __UpperCamelCase ( self ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
38
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging A_ : Tuple = logging.get_logger(__name__) # TODO: upload to AWS A_ : Tuple = { "yjernite/retribert-base-uncased": ( "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json" ), } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''retribert''' def __init__( self , __SCREAMING_SNAKE_CASE=3_0_5_2_2 , __SCREAMING_SNAKE_CASE=7_6_8 , __SCREAMING_SNAKE_CASE=8 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=3_0_7_2 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=1_2_8 , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE , ): super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : str = vocab_size snake_case__ : str = hidden_size snake_case__ : int = num_hidden_layers snake_case__ : List[Any] = num_attention_heads snake_case__ : List[Any] = hidden_act snake_case__ : Optional[Any] = intermediate_size snake_case__ : Union[str, Any] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : Tuple = max_position_embeddings snake_case__ : Optional[int] = type_vocab_size snake_case__ : str = initializer_range snake_case__ : Any = layer_norm_eps snake_case__ : Dict = share_encoders snake_case__ : str = projection_dim
38
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu A_ : Dict = [ "EAGER", "AOT_EAGER", "INDUCTOR", "NVFUSER", "AOT_NVFUSER", "AOT_CUDAGRAPHS", "OFI", "FX2TRT", "ONNXRT", "IPEX", ] def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : List[Any]=None , __magic_name__ : List[str]=None , __magic_name__ : List[str]=None ) -> Dict: '''simple docstring''' snake_case__ : Optional[int] = True while ask_again: snake_case__ : Optional[Any] = input(__magic_name__ ) try: if default is not None and len(__magic_name__ ) == 0: return default return convert_value(__magic_name__ ) if convert_value is not None else result except Exception: if error_message is not None: print(__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Any=[] , __magic_name__ : Optional[int]=None , __magic_name__ : int=0 ) -> Optional[int]: '''simple docstring''' snake_case__ : Union[str, Any] = BulletMenu(__magic_name__ , __magic_name__ ) snake_case__ : Optional[Any] = menu.run(default_choice=__magic_name__ ) return convert_value(__magic_name__ ) if convert_value is not None else result def UpperCamelCase__ ( __magic_name__ : Any ) -> int: '''simple docstring''' snake_case__ : Tuple = int(__magic_name__ ) return ComputeEnvironment(["""LOCAL_MACHINE""", """AMAZON_SAGEMAKER"""][value] ) def UpperCamelCase__ ( __magic_name__ : str ) -> Tuple: '''simple docstring''' snake_case__ : List[Any] = int(__magic_name__ ) return DistributedType(["""NO""", """MULTI_CPU""", """MULTI_XPU""", """MULTI_GPU""", """MULTI_NPU""", """TPU"""][value] ) def UpperCamelCase__ ( __magic_name__ : List[str] ) -> List[Any]: '''simple docstring''' snake_case__ : Union[str, Any] = int(__magic_name__ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def UpperCamelCase__ ( __magic_name__ : List[str] ) -> Union[str, Any]: '''simple docstring''' snake_case__ : Optional[Any] = int(__magic_name__ ) return PrecisionType(["""no""", """fp16""", """bf16""", """fp8"""][value] ) def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> List[Any]: '''simple docstring''' snake_case__ : Optional[Any] = int(__magic_name__ ) return SageMakerDistributedType(["""NO""", """DATA_PARALLEL""", """MODEL_PARALLEL"""][value] ) def UpperCamelCase__ ( __magic_name__ : Dict ) -> Tuple: '''simple docstring''' return {"yes": True, "no": False}[value.lower()] class __snake_case ( argparse.RawDescriptionHelpFormatter ): '''simple docstring''' def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : str = super()._format_usage(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : str = usage.replace("""<command> [<args>] """ , """""" ) return usage
38
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A_ : Tuple = logging.get_logger(__name__) A_ : List[str] = { "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''xlm-roberta-xl''' def __init__( self , __SCREAMING_SNAKE_CASE=2_5_0_8_8_0 , __SCREAMING_SNAKE_CASE=2_5_6_0 , __SCREAMING_SNAKE_CASE=3_6 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1_0_2_4_0 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=5_1_4 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-0_5 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=0 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE="absolute" , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = vocab_size snake_case__ : List[str] = hidden_size snake_case__ : Dict = num_hidden_layers snake_case__ : Dict = num_attention_heads snake_case__ : Optional[int] = hidden_act snake_case__ : Dict = intermediate_size snake_case__ : str = hidden_dropout_prob snake_case__ : str = attention_probs_dropout_prob snake_case__ : Any = max_position_embeddings snake_case__ : List[str] = type_vocab_size snake_case__ : List[Any] = initializer_range snake_case__ : Dict = layer_norm_eps snake_case__ : Union[str, Any] = position_embedding_type snake_case__ : Tuple = use_cache snake_case__ : int = classifier_dropout class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def __UpperCamelCase ( self ): if self.task == "multiple-choice": snake_case__ : Tuple = {0: """batch""", 1: """choice""", 2: """sequence"""} else: snake_case__ : str = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
38
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( __magic_name__ : list ) -> float: '''simple docstring''' if not nums: raise ValueError("""List is empty""" ) return sum(__magic_name__ ) / len(__magic_name__ ) if __name__ == "__main__": import doctest doctest.testmod()
38
1
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : str ) -> bool: '''simple docstring''' snake_case__ : Any = len(__magic_name__ ) snake_case__ : int = len(__magic_name__ ) snake_case__ : List[Any] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] snake_case__ : Any = True for i in range(__magic_name__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: snake_case__ : Tuple = True if a[i].islower(): snake_case__ : Dict = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
38
'''simple docstring''' from __future__ import annotations A_ : str = "Muhammad Umer Farooq" A_ : Optional[Any] = "MIT" A_ : int = "1.0.0" A_ : int = "Muhammad Umer Farooq" A_ : int = "[email protected]" A_ : Dict = "Alpha" import re from html.parser import HTMLParser from urllib import parse import requests class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): super().__init__() snake_case__ : list[str] = [] snake_case__ : List[Any] = domain def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: snake_case__ : str = parse.urljoin(self.domain , __SCREAMING_SNAKE_CASE ) self.urls.append(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return ".".join(get_sub_domain_name(__magic_name__ ).split(""".""" )[-2:] ) def UpperCamelCase__ ( __magic_name__ : str ) -> str: '''simple docstring''' return parse.urlparse(__magic_name__ ).netloc def UpperCamelCase__ ( __magic_name__ : str = "https://github.com" ) -> list[str]: '''simple docstring''' snake_case__ : List[str] = get_domain_name(__magic_name__ ) # Initialize the parser snake_case__ : Optional[Any] = Parser(__magic_name__ ) try: # Open URL snake_case__ : Any = requests.get(__magic_name__ ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through snake_case__ : List[str] = set() for link in parser.urls: # open URL. # read = requests.get(link) try: snake_case__ : Tuple = requests.get(__magic_name__ ) # Get the valid email. snake_case__ : List[str] = re.findall("""[a-zA-Z0-9]+@""" + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(__magic_name__ ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(__magic_name__ ) if __name__ == "__main__": A_ : str = emails_from_url("https://github.com") print(F'{len(emails)} emails found:') print("\n".join(sorted(emails)))
38
1
'''simple docstring''' import random import unittest import torch from diffusers import IFImgaImgSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = IFImgaImgSuperResolutionPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''width''', '''height'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''original_image'''} ) lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} def __UpperCamelCase ( self ): return self._get_superresolution_dummy_components() def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): snake_case__ : List[Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case__ : Tuple = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = floats_tensor((1, 3, 1_6, 1_6) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : int = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """original_image""": original_image, """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def __UpperCamelCase ( self ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def __UpperCamelCase ( self ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != """cuda""" , reason="""float16 requires CUDA""" ) def __UpperCamelCase ( self ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def __UpperCamelCase ( self ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def __UpperCamelCase ( self ): self._test_save_load_local() def __UpperCamelCase ( self ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
38
'''simple docstring''' def UpperCamelCase__ ( __magic_name__ : List[Any] ) -> Tuple: '''simple docstring''' if not head: return True # split the list to two parts snake_case__ , snake_case__ : Dict = head.next, head while fast and fast.next: snake_case__ : Any = fast.next.next snake_case__ : int = slow.next snake_case__ : Dict = slow.next snake_case__ : List[str] = None # Don't forget here! But forget still works! # reverse the second part snake_case__ : Tuple = None while second: snake_case__ : Tuple = second.next snake_case__ : Any = node snake_case__ : str = second snake_case__ : Optional[Any] = nxt # compare two parts # second part has the same or one less node while node: if node.val != head.val: return False snake_case__ : List[Any] = node.next snake_case__ : int = head.next return True def UpperCamelCase__ ( __magic_name__ : Any ) -> Optional[Any]: '''simple docstring''' if not head or not head.next: return True # 1. Get the midpoint (slow) snake_case__ : List[Any] = head while fast and fast.next: snake_case__ , snake_case__ : Any = fast.next.next, slow.next # 2. Push the second half into the stack snake_case__ : Tuple = [slow.val] while slow.next: snake_case__ : Optional[Any] = slow.next stack.append(slow.val ) # 3. Comparison while stack: if stack.pop() != cur.val: return False snake_case__ : str = cur.next return True def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Tuple: '''simple docstring''' if not head or not head.next: return True snake_case__ : int = {} snake_case__ : Union[str, Any] = 0 while head: if head.val in d: d[head.val].append(__magic_name__ ) else: snake_case__ : Tuple = [pos] snake_case__ : Optional[Any] = head.next pos += 1 snake_case__ : int = pos - 1 snake_case__ : str = 0 for v in d.values(): if len(__magic_name__ ) % 2 != 0: middle += 1 else: snake_case__ : List[str] = 0 for i in range(0 , len(__magic_name__ ) ): if v[i] + v[len(__magic_name__ ) - 1 - step] != checksum: return False step += 1 if middle > 1: return False return True
38
1
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> str: '''simple docstring''' snake_case__ : List[str] = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( """`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got """ f"{test_file} instead." ) snake_case__ : Tuple = components[-1] if not test_fn.endswith("""py""" ): raise ValueError(f"`test_file` should be a python file. Got {test_fn} instead." ) if not test_fn.startswith("""test_modeling_""" ): raise ValueError( f"`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead." ) snake_case__ : Optional[Any] = components[:-1] + [test_fn.replace(""".py""" , """""" )] snake_case__ : List[str] = """.""".join(__magic_name__ ) return test_module_path def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> Dict: '''simple docstring''' snake_case__ : str = get_module_path(__magic_name__ ) snake_case__ : Optional[Any] = importlib.import_module(__magic_name__ ) return test_module def UpperCamelCase__ ( __magic_name__ : str ) -> Optional[Any]: '''simple docstring''' snake_case__ : Any = [] snake_case__ : Any = get_test_module(__magic_name__ ) for attr in dir(__magic_name__ ): if attr.endswith("""ModelTester""" ): tester_classes.append(getattr(__magic_name__ , __magic_name__ ) ) # sort with class names return sorted(__magic_name__ , key=lambda __magic_name__ : x.__name__ ) def UpperCamelCase__ ( __magic_name__ : Any ) -> Optional[int]: '''simple docstring''' snake_case__ : Union[str, Any] = [] snake_case__ : Union[str, Any] = get_test_module(__magic_name__ ) for attr in dir(__magic_name__ ): snake_case__ : List[str] = getattr(__magic_name__ , __magic_name__ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). snake_case__ : Any = getattr(__magic_name__ , """all_model_classes""" , [] ) if len(__magic_name__ ) > 0: test_classes.append(__magic_name__ ) # sort with class names return sorted(__magic_name__ , key=lambda __magic_name__ : x.__name__ ) def UpperCamelCase__ ( __magic_name__ : Optional[int] ) -> List[str]: '''simple docstring''' snake_case__ : Optional[Any] = get_test_classes(__magic_name__ ) snake_case__ : Union[str, Any] = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(__magic_name__ , key=lambda __magic_name__ : x.__name__ ) def UpperCamelCase__ ( __magic_name__ : str ) -> Optional[Any]: '''simple docstring''' snake_case__ : Optional[int] = test_class() if hasattr(__magic_name__ , """setUp""" ): test.setUp() snake_case__ : List[Any] = None if hasattr(__magic_name__ , """model_tester""" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: snake_case__ : Optional[Any] = test.model_tester.__class__ return model_tester def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : int ) -> Dict: '''simple docstring''' snake_case__ : List[str] = get_test_classes(__magic_name__ ) snake_case__ : str = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(__magic_name__ ) # sort with class names return sorted(__magic_name__ , key=lambda __magic_name__ : x.__name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Dict ) -> Optional[int]: '''simple docstring''' snake_case__ : Tuple = get_test_classes_for_model(__magic_name__ , __magic_name__ ) snake_case__ : List[Any] = [] for test_class in test_classes: snake_case__ : List[str] = get_model_tester_from_test_class(__magic_name__ ) if tester_class is not None: tester_classes.append(__magic_name__ ) # sort with class names return sorted(__magic_name__ , key=lambda __magic_name__ : x.__name__ ) def UpperCamelCase__ ( __magic_name__ : Tuple ) -> Optional[int]: '''simple docstring''' snake_case__ : List[Any] = get_test_classes(__magic_name__ ) snake_case__ : Union[str, Any] = {test_class: get_model_tester_from_test_class(__magic_name__ ) for test_class in test_classes} return test_tester_mapping def UpperCamelCase__ ( __magic_name__ : Tuple ) -> str: '''simple docstring''' snake_case__ : Any = get_model_classes(__magic_name__ ) snake_case__ : str = { model_class: get_test_classes_for_model(__magic_name__ , __magic_name__ ) for model_class in model_classes } return model_test_mapping def UpperCamelCase__ ( __magic_name__ : Dict ) -> Union[str, Any]: '''simple docstring''' snake_case__ : int = get_model_classes(__magic_name__ ) snake_case__ : Union[str, Any] = { model_class: get_tester_classes_for_model(__magic_name__ , __magic_name__ ) for model_class in model_classes } return model_to_tester_mapping def UpperCamelCase__ ( __magic_name__ : Tuple ) -> Any: '''simple docstring''' if isinstance(__magic_name__ , __magic_name__ ): return o elif isinstance(__magic_name__ , __magic_name__ ): return o.__name__ elif isinstance(__magic_name__ , (list, tuple) ): return [to_json(__magic_name__ ) for x in o] elif isinstance(__magic_name__ , __magic_name__ ): return {to_json(__magic_name__ ): to_json(__magic_name__ ) for k, v in o.items()} else: return o
38
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin A_ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A_ : str = 250004 A_ : str = 250020 @require_sentencepiece @require_tokenizers class __snake_case ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = MBartTokenizer lowerCamelCase__ = MBartTokenizerFast lowerCamelCase__ = True lowerCamelCase__ = True def __UpperCamelCase ( self ): super().setUp() # We have a SentencePiece fixture for testing snake_case__ : Tuple = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self ): snake_case__ : Tuple = MBartTokenizer(__SCREAMING_SNAKE_CASE , keep_accents=__SCREAMING_SNAKE_CASE ) snake_case__ : int = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(__SCREAMING_SNAKE_CASE , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) snake_case__ : Optional[int] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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""", """é""", """.""", ] , ) snake_case__ : Optional[int] = tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) snake_case__ : Union[str, Any] = tokenizer.convert_ids_to_tokens(__SCREAMING_SNAKE_CASE ) self.assertListEqual( __SCREAMING_SNAKE_CASE , [ 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 __UpperCamelCase ( self ): if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return snake_case__ : Optional[int] = (self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): snake_case__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = tempfile.mkdtemp() snake_case__ : int = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) snake_case__ : List[str] = tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f ) self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way snake_case__ : Tuple = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=True snake_case__ : Any = tempfile.mkdtemp() snake_case__ : Optional[int] = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) snake_case__ : int = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it save with the same files self.assertSequenceEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # Checks everything loads correctly in the same way snake_case__ : List[Any] = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) # Save tokenizer rust, legacy_format=False snake_case__ : Dict = tempfile.mkdtemp() snake_case__ : Union[str, Any] = tokenizer_r.save_pretrained(__SCREAMING_SNAKE_CASE , legacy_format=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = tokenizer_p.save_pretrained(__SCREAMING_SNAKE_CASE ) # Checks it saved the tokenizer.json file self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way snake_case__ : Dict = tokenizer_r.from_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = tokenizer_p.from_pretrained(__SCREAMING_SNAKE_CASE ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) ) shutil.rmtree(__SCREAMING_SNAKE_CASE ) @require_torch @require_sentencepiece @require_tokenizers class __snake_case ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = '''facebook/mbart-large-en-ro''' lowerCamelCase__ = [ ''' UN Chief Says There Is No Military Solution in Syria''', ''' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.''', ] lowerCamelCase__ = [ '''Şeful ONU declară că nu există o soluţie militară în Siria''', '''Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei''' ''' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor''' ''' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.''', ] lowerCamelCase__ = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE] @classmethod def __UpperCamelCase ( cls ): snake_case__ : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="""en_XX""" , tgt_lang="""ro_RO""" ) snake_case__ : Any = 1 return cls def __UpperCamelCase ( self ): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""] , 2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""] , 2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""] , 2_5_0_0_2_0 ) def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.assertIn(__SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids ) snake_case__ : List[str] = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] snake_case__ : List[Any] = self.tokenizer.decode(__SCREAMING_SNAKE_CASE , skip_special_tokens=__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__SCREAMING_SNAKE_CASE ) self.assertEqual(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertNotIn(self.tokenizer.eos_token , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = ["""this is gunna be a long sentence """ * 2_0] assert isinstance(src_text[0] , __SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = 1_0 snake_case__ : int = self.tokenizer(__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , __SCREAMING_SNAKE_CASE ) self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""] ) , [2_5_0_0_2_6, 2_5_0_0_0_1] ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = tempfile.mkdtemp() snake_case__ : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = MBartTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __SCREAMING_SNAKE_CASE ) @require_torch def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ) snake_case__ : int = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=len(self.expected_src_tokens ) , return_tensors="""pt""" , ) snake_case__ : List[str] = shift_tokens_right(batch["""labels"""] , self.tokenizer.pad_token_id ) self.assertIsInstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.assertEqual((2, 1_4) , batch.input_ids.shape ) self.assertEqual((2, 1_4) , batch.attention_mask.shape ) snake_case__ : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __SCREAMING_SNAKE_CASE ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def __UpperCamelCase ( self ): snake_case__ : Optional[int] = self.tokenizer(self.src_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=3 , return_tensors="""pt""" ) snake_case__ : Optional[int] = self.tokenizer( text_target=self.tgt_text , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=1_0 , return_tensors="""pt""" ) snake_case__ : str = targets["""input_ids"""] snake_case__ : Optional[Any] = shift_tokens_right(__SCREAMING_SNAKE_CASE , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def __UpperCamelCase ( self ): snake_case__ : Tuple = self.tokenizer._build_translation_inputs( """A test""" , return_tensors="""pt""" , src_lang="""en_XX""" , tgt_lang="""ar_AR""" ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE ) , { # A, test, EOS, en_XX """input_ids""": [[6_2, 3_0_3_4, 2, 2_5_0_0_0_4]], """attention_mask""": [[1, 1, 1, 1]], # ar_AR """forced_bos_token_id""": 2_5_0_0_0_1, } , )
38
1
'''simple docstring''' from __future__ import annotations class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = order # a_{0} ... a_{k} snake_case__ : Union[str, Any] = [1.0] + [0.0] * order # b_{0} ... b_{k} snake_case__ : Tuple = [1.0] + [0.0] * order # x[n-1] ... x[n-k] snake_case__ : Union[str, Any] = [0.0] * self.order # y[n-1] ... y[n-k] snake_case__ : int = [0.0] * self.order def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): if len(__SCREAMING_SNAKE_CASE ) < self.order: snake_case__ : Dict = [1.0, *a_coeffs] if len(__SCREAMING_SNAKE_CASE ) != self.order + 1: snake_case__ : List[Any] = ( f"Expected a_coeffs to have {self.order + 1} elements " f"for {self.order}-order filter, got {len(__SCREAMING_SNAKE_CASE )}" ) raise ValueError(__SCREAMING_SNAKE_CASE ) if len(__SCREAMING_SNAKE_CASE ) != self.order + 1: snake_case__ : Optional[Any] = ( f"Expected b_coeffs to have {self.order + 1} elements " f"for {self.order}-order filter, got {len(__SCREAMING_SNAKE_CASE )}" ) raise ValueError(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = a_coeffs snake_case__ : List[Any] = b_coeffs def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Union[str, Any] = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) snake_case__ : Any = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] snake_case__ : Optional[Any] = self.input_history[:-1] snake_case__ : Dict = self.output_history[:-1] snake_case__ : Dict = sample snake_case__ : List[str] = result return result
38
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : int = logging.get_logger(__name__) A_ : Dict = { "google/bit-50": "https://huggingface.co/google/bit-50/resolve/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''bit''' lowerCamelCase__ = ['''preactivation''', '''bottleneck'''] lowerCamelCase__ = ['''SAME''', '''VALID'''] def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=6_4 , __SCREAMING_SNAKE_CASE=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8] , __SCREAMING_SNAKE_CASE=[3, 4, 6, 3] , __SCREAMING_SNAKE_CASE="preactivation" , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) if layer_type not in self.layer_types: raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types )}" ) if global_padding is not None: if global_padding.upper() in self.supported_padding: snake_case__ : Tuple = global_padding.upper() else: raise ValueError(f"Padding strategy {global_padding} not supported" ) snake_case__ : List[str] = num_channels snake_case__ : Tuple = embedding_size snake_case__ : str = hidden_sizes snake_case__ : Optional[Any] = depths snake_case__ : List[Any] = layer_type snake_case__ : Dict = hidden_act snake_case__ : Union[str, Any] = global_padding snake_case__ : List[str] = num_groups snake_case__ : str = drop_path_rate snake_case__ : List[Any] = embedding_dynamic_padding snake_case__ : List[str] = output_stride snake_case__ : Dict = width_factor snake_case__ : List[str] = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] snake_case__ , snake_case__ : Dict = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
38
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices A_ : Dict = logging.get_logger(__name__) A_ : Optional[Any] = { "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = '''convnextv2''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=1e-1_2 , __SCREAMING_SNAKE_CASE=0.0 , __SCREAMING_SNAKE_CASE=2_2_4 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ): super().__init__(**__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] = num_channels snake_case__ : str = patch_size snake_case__ : List[Any] = num_stages snake_case__ : Optional[Any] = [9_6, 1_9_2, 3_8_4, 7_6_8] if hidden_sizes is None else hidden_sizes snake_case__ : Dict = [3, 3, 9, 3] if depths is None else depths snake_case__ : List[str] = hidden_act snake_case__ : str = initializer_range snake_case__ : Tuple = layer_norm_eps snake_case__ : int = drop_path_rate snake_case__ : Dict = image_size snake_case__ : Optional[int] = ["""stem"""] + [f"stage{idx}" for idx in range(1 , len(self.depths ) + 1 )] snake_case__ , snake_case__ : Optional[int] = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
38
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() A_ : Optional[int] = logging.get_logger(__name__) def UpperCamelCase__ ( __magic_name__ : Optional[Any] , __magic_name__ : str=False ) -> Tuple: '''simple docstring''' snake_case__ : int = [] # fmt: off # stem: rename_keys.append(("""cls_token""", """vit.embeddings.cls_token""") ) rename_keys.append(("""pos_embed""", """vit.embeddings.position_embeddings""") ) rename_keys.append(("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias""") ) # backbone rename_keys.append(("""patch_embed.backbone.stem.conv.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.weight""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight""") ) rename_keys.append(("""patch_embed.backbone.stem.norm.bias""", """vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias""") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias") ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case__ : List[Any] = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) # fmt: on return rename_keys def UpperCamelCase__ ( __magic_name__ : Tuple , __magic_name__ : int , __magic_name__ : Tuple=False ) -> str: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: snake_case__ : int = """""" else: snake_case__ : Dict = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case__ : int = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) snake_case__ : Union[str, Any] = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] snake_case__ : Optional[Any] = in_proj_bias[: config.hidden_size] snake_case__ : List[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case__ : List[Any] = in_proj_weight[ -config.hidden_size :, : ] snake_case__ : Optional[int] = in_proj_bias[-config.hidden_size :] def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> List[str]: '''simple docstring''' snake_case__ : str = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(__magic_name__ , __magic_name__ ) def UpperCamelCase__ ( __magic_name__ : List[str] , __magic_name__ : Union[str, Any] , __magic_name__ : str ) -> Union[str, Any]: '''simple docstring''' snake_case__ : List[str] = dct.pop(__magic_name__ ) snake_case__ : Dict = val def UpperCamelCase__ ( ) -> str: '''simple docstring''' snake_case__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case__ : Optional[int] = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) return im @torch.no_grad() def UpperCamelCase__ ( __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : int=False ) -> Optional[int]: '''simple docstring''' snake_case__ : int = BitConfig( global_padding="""same""" , layer_type="""bottleneck""" , depths=(3, 4, 9) , out_features=["""stage3"""] , embedding_dynamic_padding=__magic_name__ , ) snake_case__ : Optional[int] = ViTHybridConfig(backbone_config=__magic_name__ , image_size=3_84 , num_labels=10_00 ) snake_case__ : Union[str, Any] = False # load original model from timm snake_case__ : List[Any] = timm.create_model(__magic_name__ , pretrained=__magic_name__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case__ : Optional[int] = timm_model.state_dict() if base_model: remove_classification_head_(__magic_name__ ) snake_case__ : int = create_rename_keys(__magic_name__ , __magic_name__ ) for src, dest in rename_keys: rename_key(__magic_name__ , __magic_name__ , __magic_name__ ) read_in_q_k_v(__magic_name__ , __magic_name__ , __magic_name__ ) snake_case__ : str = """huggingface/label-files""" snake_case__ : Union[str, Any] = """imagenet-1k-id2label.json""" snake_case__ : Dict = json.load(open(hf_hub_download(__magic_name__ , __magic_name__ , repo_type="""dataset""" ) , """r""" ) ) snake_case__ : List[Any] = {int(__magic_name__ ): v for k, v in idalabel.items()} snake_case__ : int = idalabel snake_case__ : str = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": snake_case__ : str = ViTHybridModel(__magic_name__ ).eval() else: snake_case__ : Union[str, Any] = ViTHybridForImageClassification(__magic_name__ ).eval() model.load_state_dict(__magic_name__ ) # create image processor snake_case__ : Optional[Any] = create_transform(**resolve_data_config({} , model=__magic_name__ ) ) snake_case__ : Union[str, Any] = transform.transforms snake_case__ : Tuple = { """bilinear""": PILImageResampling.BILINEAR, """bicubic""": PILImageResampling.BICUBIC, """nearest""": PILImageResampling.NEAREST, } snake_case__ : Any = ViTHybridImageProcessor( do_resize=__magic_name__ , size={"""shortest_edge""": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=__magic_name__ , crop_size={"""height""": timm_transforms[1].size[0], """width""": timm_transforms[1].size[1]} , do_normalize=__magic_name__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) snake_case__ : Any = prepare_img() snake_case__ : int = transform(__magic_name__ ).unsqueeze(0 ) snake_case__ : List[str] = processor(__magic_name__ , return_tensors="""pt""" ).pixel_values # verify pixel values assert torch.allclose(__magic_name__ , __magic_name__ ) # verify logits with torch.no_grad(): snake_case__ : Optional[Any] = model(__magic_name__ ) snake_case__ : Union[str, Any] = outputs.logits print("""Predicted class:""" , logits.argmax(-1 ).item() ) if base_model: snake_case__ : Dict = timm_model.forward_features(__magic_name__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(__magic_name__ , outputs.pooler_output , atol=1E-3 ) else: snake_case__ : int = timm_model(__magic_name__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__magic_name__ , outputs.logits , atol=1E-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(__magic_name__ ) if push_to_hub: print(f"Pushing model and processor to the hub {vit_name}" ) model.push_to_hub(f"ybelkada/{vit_name}" ) processor.push_to_hub(f"ybelkada/{vit_name}" ) if __name__ == "__main__": A_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) A_ : Union[str, Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
38
1
'''simple docstring''' import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import numpy as np import pandas as pd from datasets import load_dataset import transformers from transformers import ( AutoConfig, BartForSequenceClassification, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, TapexTokenizer, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.17.0.dev0") require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt") A_ : Tuple = logging.getLogger(__name__) @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default='''tab_fact''' , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) lowerCamelCase__ = field( default='''tab_fact''' , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} , ) lowerCamelCase__ = field( default=1_024 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''} ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) } , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of prediction examples to this ''' '''value if set.''' ) } , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''A csv or a json file containing the training data.'''} ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''A csv or a json file containing the validation data.'''} ) lowerCamelCase__ = field(default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''A csv or a json file containing the test data.'''} ) def __UpperCamelCase ( self ): if self.dataset_name is not None: pass elif self.train_file is None or self.validation_file is None: raise ValueError("""Need either a GLUE task, a training/validation file or a dataset name.""" ) else: snake_case__ : str = self.train_file.split(""".""" )[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." snake_case__ : List[str] = self.validation_file.split(""".""" )[-1] assert ( validation_extension == train_extension ), "`validation_file` should have the same extension (csv or json) as `train_file`." @dataclass class __snake_case : '''simple docstring''' lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) lowerCamelCase__ = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) lowerCamelCase__ = field( default=__SCREAMING_SNAKE_CASE , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) def UpperCamelCase__ ( ) -> int: '''simple docstring''' snake_case__ : Any = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case__ , snake_case__ , snake_case__ : Any = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case__ , snake_case__ , snake_case__ : Optional[Any] = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) snake_case__ : str = training_args.get_process_log_level() logger.setLevel(__magic_name__ ) datasets.utils.logging.set_verbosity(__magic_name__ ) transformers.utils.logging.set_verbosity(__magic_name__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Detecting last checkpoint. snake_case__ : Any = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case__ : Dict = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. snake_case__ : Tuple = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir ) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. snake_case__ : List[str] = {"""train""": data_args.train_file, """validation""": data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: snake_case__ : int = data_args.train_file.split(""".""" )[-1] snake_case__ : int = data_args.test_file.split(""".""" )[-1] assert ( test_extension == train_extension ), "`test_file` should have the same extension (csv or json) as `train_file`." snake_case__ : List[str] = data_args.test_file else: raise ValueError("""Need either a GLUE task or a test file for `do_predict`.""" ) for key in data_files.keys(): logger.info(f"load a local file for {key}: {data_files[key]}" ) if data_args.train_file.endswith(""".csv""" ): # Loading a dataset from local csv files snake_case__ : int = load_dataset("""csv""" , data_files=__magic_name__ , cache_dir=model_args.cache_dir ) else: # Loading a dataset from local json files snake_case__ : Tuple = load_dataset("""json""" , data_files=__magic_name__ , cache_dir=model_args.cache_dir ) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets.html. # Labels snake_case__ : Dict = raw_datasets["""train"""].features["""label"""].names snake_case__ : Optional[Any] = len(__magic_name__ ) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case__ : int = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=__magic_name__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # load tapex tokenizer snake_case__ : Dict = TapexTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=__magic_name__ , ) snake_case__ : Tuple = BartForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__magic_name__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Padding strategy if data_args.pad_to_max_length: snake_case__ : Dict = """max_length""" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch snake_case__ : Dict = False # Some models have set the order of the labels to use, so let's make sure we do use it. snake_case__ : Union[str, Any] = {"""Refused""": 0, """Entailed""": 1} snake_case__ : List[str] = {0: """Refused""", 1: """Entailed"""} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"The max_seq_length passed ({data_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}." ) snake_case__ : int = min(data_args.max_seq_length , tokenizer.model_max_length ) def preprocess_tabfact_function(__magic_name__ : Union[str, Any] ): # Tokenize the texts def _convert_table_text_to_pandas(__magic_name__ : int ): snake_case__ : List[Any] = [_table_row.split("""#""" ) for _table_row in _table_text.strip("""\n""" ).split("""\n""" )] snake_case__ : Optional[Any] = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] ) return _table_pd snake_case__ : Optional[int] = examples["""statement"""] snake_case__ : Dict = list(map(_convert_table_text_to_pandas , examples["""table_text"""] ) ) snake_case__ : Optional[Any] = tokenizer(__magic_name__ , __magic_name__ , padding=__magic_name__ , max_length=__magic_name__ , truncation=__magic_name__ ) snake_case__ : Tuple = examples["""label"""] return result with training_args.main_process_first(desc="""dataset map pre-processing""" ): snake_case__ : List[str] = raw_datasets.map( __magic_name__ , batched=__magic_name__ , load_from_cache_file=not data_args.overwrite_cache , desc="""Running tokenizer on dataset""" , ) if training_args.do_train: if "train" not in raw_datasets: raise ValueError("""--do_train requires a train dataset""" ) snake_case__ : Optional[int] = raw_datasets["""train"""] if data_args.max_train_samples is not None: snake_case__ : List[Any] = train_dataset.select(range(data_args.max_train_samples ) ) if training_args.do_eval: if "validation" not in raw_datasets and "validation_matched" not in raw_datasets: raise ValueError("""--do_eval requires a validation dataset""" ) snake_case__ : int = raw_datasets["""validation"""] if data_args.max_eval_samples is not None: snake_case__ : Any = eval_dataset.select(range(data_args.max_eval_samples ) ) if training_args.do_predict or data_args.test_file is not None: if "test" not in raw_datasets and "test_matched" not in raw_datasets: raise ValueError("""--do_predict requires a test dataset""" ) snake_case__ : List[Any] = raw_datasets["""test"""] if data_args.max_predict_samples is not None: snake_case__ : Dict = predict_dataset.select(range(data_args.max_predict_samples ) ) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(__magic_name__ ) ) , 3 ): logger.info(f"Sample {index} of the training set: {train_dataset[index]}." ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(__magic_name__ : EvalPrediction ): snake_case__ : Union[str, Any] = p.predictions[0] if isinstance(p.predictions , __magic_name__ ) else p.predictions snake_case__ : Union[str, Any] = np.argmax(__magic_name__ , axis=1 ) return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: snake_case__ : Union[str, Any] = default_data_collator elif training_args.fpaa: snake_case__ : Optional[int] = DataCollatorWithPadding(__magic_name__ , pad_to_multiple_of=8 ) else: snake_case__ : str = None # Initialize our Trainer snake_case__ : str = Trainer( model=__magic_name__ , args=__magic_name__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=__magic_name__ , tokenizer=__magic_name__ , data_collator=__magic_name__ , ) # Training if training_args.do_train: snake_case__ : Optional[Any] = None if training_args.resume_from_checkpoint is not None: snake_case__ : Tuple = training_args.resume_from_checkpoint elif last_checkpoint is not None: snake_case__ : Optional[int] = last_checkpoint snake_case__ : Any = trainer.train(resume_from_checkpoint=__magic_name__ ) snake_case__ : str = train_result.metrics snake_case__ : Dict = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(__magic_name__ ) ) snake_case__ : Any = min(__magic_name__ , len(__magic_name__ ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("""train""" , __magic_name__ ) trainer.save_metrics("""train""" , __magic_name__ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("""*** Evaluate ***""" ) snake_case__ : Optional[Any] = trainer.evaluate(eval_dataset=__magic_name__ ) snake_case__ : Union[str, Any] = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__magic_name__ ) snake_case__ : List[str] = min(__magic_name__ , len(__magic_name__ ) ) trainer.log_metrics("""eval""" , __magic_name__ ) trainer.save_metrics("""eval""" , __magic_name__ ) if training_args.do_predict: logger.info("""*** Predict ***""" ) # Removing the `label` columns because it contains -1 and Trainer won't like that. snake_case__ : Dict = predict_dataset.remove_columns("""label""" ) snake_case__ : str = trainer.predict(__magic_name__ , metric_key_prefix="""predict""" ).predictions snake_case__ : str = np.argmax(__magic_name__ , axis=1 ) snake_case__ : Tuple = os.path.join(training_args.output_dir , """predict_results_tabfact.txt""" ) if trainer.is_world_process_zero(): with open(__magic_name__ , """w""" ) as writer: logger.info("""***** Predict Results *****""" ) writer.write("""index\tprediction\n""" ) for index, item in enumerate(__magic_name__ ): snake_case__ : List[str] = label_list[item] writer.write(f"{index}\t{item}\n" ) snake_case__ : Union[str, Any] = {"""finetuned_from""": model_args.model_name_or_path, """tasks""": """text-classification"""} if training_args.push_to_hub: trainer.push_to_hub(**__magic_name__ ) else: trainer.create_model_card(**__magic_name__ ) def UpperCamelCase__ ( __magic_name__ : str ) -> List[str]: '''simple docstring''' main() if __name__ == "__main__": main()
38
'''simple docstring''' from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowerCamelCase__ = 42 class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("DownEncoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE=True , ): super().__init__() snake_case__ : str = layers_per_block snake_case__ : int = torch.nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : List[Any] = None snake_case__ : List[Any] = nn.ModuleList([] ) # down snake_case__ : Union[str, Any] = block_out_channels[0] for i, down_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = output_channel snake_case__ : Union[str, Any] = block_out_channels[i] snake_case__ : int = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : str = get_down_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , add_downsample=not is_final_block , resnet_eps=1e-6 , downsample_padding=0 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) self.down_blocks.append(__SCREAMING_SNAKE_CASE ) # mid snake_case__ : Optional[Any] = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # out snake_case__ : Tuple = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : str = 2 * out_channels if double_z else out_channels snake_case__ : int = nn.Convad(block_out_channels[-1] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : Union[str, Any] = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = x snake_case__ : int = self.conv_in(__SCREAMING_SNAKE_CASE ) if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) # middle snake_case__ : List[Any] = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: for down_block in self.down_blocks: snake_case__ : Dict = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE ) else: # down for down_block in self.down_blocks: snake_case__ : List[str] = down_block(__SCREAMING_SNAKE_CASE ) # middle snake_case__ : str = self.mid_block(__SCREAMING_SNAKE_CASE ) # post-process snake_case__ : Any = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : str = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=("UpDecoderBlock2D",) , __SCREAMING_SNAKE_CASE=(6_4,) , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE="silu" , __SCREAMING_SNAKE_CASE="group" , ): super().__init__() snake_case__ : Any = layers_per_block snake_case__ : Optional[Any] = nn.Convad( __SCREAMING_SNAKE_CASE , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) snake_case__ : Union[str, Any] = None snake_case__ : Dict = nn.ModuleList([] ) snake_case__ : Optional[int] = in_channels if norm_type == """spatial""" else None # mid snake_case__ : Tuple = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , ) # up snake_case__ : List[Any] = list(reversed(__SCREAMING_SNAKE_CASE ) ) snake_case__ : Optional[Any] = reversed_block_out_channels[0] for i, up_block_type in enumerate(__SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = output_channel snake_case__ : Optional[Any] = reversed_block_out_channels[i] snake_case__ : List[str] = i == len(__SCREAMING_SNAKE_CASE ) - 1 snake_case__ : int = get_up_block( __SCREAMING_SNAKE_CASE , num_layers=self.layers_per_block + 1 , in_channels=__SCREAMING_SNAKE_CASE , out_channels=__SCREAMING_SNAKE_CASE , prev_output_channel=__SCREAMING_SNAKE_CASE , add_upsample=not is_final_block , resnet_eps=1e-6 , resnet_act_fn=__SCREAMING_SNAKE_CASE , resnet_groups=__SCREAMING_SNAKE_CASE , attention_head_dim=__SCREAMING_SNAKE_CASE , temb_channels=__SCREAMING_SNAKE_CASE , resnet_time_scale_shift=__SCREAMING_SNAKE_CASE , ) self.up_blocks.append(__SCREAMING_SNAKE_CASE ) snake_case__ : int = output_channel # out if norm_type == "spatial": snake_case__ : List[Any] = SpatialNorm(block_out_channels[0] , __SCREAMING_SNAKE_CASE ) else: snake_case__ : Any = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__SCREAMING_SNAKE_CASE , eps=1e-6 ) snake_case__ : Tuple = nn.SiLU() snake_case__ : Union[str, Any] = nn.Convad(block_out_channels[0] , __SCREAMING_SNAKE_CASE , 3 , padding=1 ) snake_case__ : int = False def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ): snake_case__ : Union[str, Any] = z snake_case__ : Any = self.conv_in(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__SCREAMING_SNAKE_CASE ): def custom_forward(*__SCREAMING_SNAKE_CASE ): return module(*__SCREAMING_SNAKE_CASE ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle snake_case__ : int = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) snake_case__ : int = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : List[str] = torch.utils.checkpoint.checkpoint( create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , use_reentrant=__SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : Dict = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : str = torch.utils.checkpoint.checkpoint(create_custom_forward(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else: # middle snake_case__ : List[Any] = self.mid_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = sample.to(__SCREAMING_SNAKE_CASE ) # up for up_block in self.up_blocks: snake_case__ : Dict = up_block(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) # post-process if latent_embeds is None: snake_case__ : Optional[Any] = self.conv_norm_out(__SCREAMING_SNAKE_CASE ) else: snake_case__ : str = self.conv_norm_out(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Any = self.conv_act(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = self.conv_out(__SCREAMING_SNAKE_CASE ) return sample class __snake_case ( nn.Module ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE="random" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=True ): super().__init__() snake_case__ : int = n_e snake_case__ : Optional[int] = vq_embed_dim snake_case__ : int = beta snake_case__ : Optional[int] = legacy snake_case__ : Dict = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) snake_case__ : List[str] = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) snake_case__ : Optional[Any] = self.used.shape[0] snake_case__ : List[str] = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": snake_case__ : Dict = self.re_embed snake_case__ : List[str] = self.re_embed + 1 print( f"Remapping {self.n_e} indices to {self.re_embed} indices. " f"Using {self.unknown_index} for unknown indices." ) else: snake_case__ : Union[str, Any] = n_e snake_case__ : str = sane_index_shape def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : Dict = inds.reshape(ishape[0] , -1 ) snake_case__ : Any = self.used.to(__SCREAMING_SNAKE_CASE ) snake_case__ : Dict = (inds[:, :, None] == used[None, None, ...]).long() snake_case__ : List[Any] = match.argmax(-1 ) snake_case__ : List[str] = match.sum(2 ) < 1 if self.unknown_index == "random": snake_case__ : List[str] = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: snake_case__ : Optional[Any] = self.unknown_index return new.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): snake_case__ : List[Any] = inds.shape assert len(__SCREAMING_SNAKE_CASE ) > 1 snake_case__ : int = inds.reshape(ishape[0] , -1 ) snake_case__ : Optional[int] = self.used.to(__SCREAMING_SNAKE_CASE ) if self.re_embed > self.used.shape[0]: # extra token snake_case__ : List[Any] = 0 # simply set to zero snake_case__ : Union[str, Any] = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __SCREAMING_SNAKE_CASE ) return back.reshape(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE ): # reshape z -> (batch, height, width, channel) and flatten snake_case__ : Any = z.permute(0 , 2 , 3 , 1 ).contiguous() snake_case__ : Optional[Any] = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z snake_case__ : Dict = torch.argmin(torch.cdist(__SCREAMING_SNAKE_CASE , self.embedding.weight ) , dim=1 ) snake_case__ : Union[str, Any] = self.embedding(__SCREAMING_SNAKE_CASE ).view(z.shape ) snake_case__ : List[str] = None snake_case__ : Union[str, Any] = None # compute loss for embedding if not self.legacy: snake_case__ : Tuple = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: snake_case__ : List[Any] = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients snake_case__ : Any = z + (z_q - z).detach() # reshape back to match original input shape snake_case__ : Union[str, Any] = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: snake_case__ : List[Any] = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis snake_case__ : str = self.remap_to_used(__SCREAMING_SNAKE_CASE ) snake_case__ : str = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: snake_case__ : Tuple = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): # shape specifying (batch, height, width, channel) if self.remap is not None: snake_case__ : List[Any] = indices.reshape(shape[0] , -1 ) # add batch axis snake_case__ : Optional[int] = self.unmap_to_all(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = indices.reshape(-1 ) # flatten again # get quantized latent vectors snake_case__ : int = self.embedding(__SCREAMING_SNAKE_CASE ) if shape is not None: snake_case__ : str = z_q.view(__SCREAMING_SNAKE_CASE ) # reshape back to match original input shape snake_case__ : str = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): snake_case__ : Tuple = parameters snake_case__ , snake_case__ : Any = torch.chunk(__SCREAMING_SNAKE_CASE , 2 , dim=1 ) snake_case__ : Union[str, Any] = torch.clamp(self.logvar , -30.0 , 20.0 ) snake_case__ : Optional[int] = deterministic snake_case__ : Optional[int] = torch.exp(0.5 * self.logvar ) snake_case__ : Any = torch.exp(self.logvar ) if self.deterministic: snake_case__ : List[str] = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE = None ): # make sure sample is on the same device as the parameters and has same dtype snake_case__ : Dict = randn_tensor( self.mean.shape , generator=__SCREAMING_SNAKE_CASE , device=self.parameters.device , dtype=self.parameters.dtype ) snake_case__ : Optional[int] = self.mean + self.std * sample return x def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE=None ): if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=[1, 2, 3] ): if self.deterministic: return torch.Tensor([0.0] ) snake_case__ : Any = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): return self.mean
38
1
'''simple docstring''' from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput A_ : Tuple = 8 def UpperCamelCase__ ( __magic_name__ : str , __magic_name__ : Optional[int]=BITS ) -> List[Any]: '''simple docstring''' snake_case__ : List[str] = x.device snake_case__ : Union[str, Any] = (x * 2_55).int().clamp(0 , 2_55 ) snake_case__ : Optional[Any] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__magic_name__ ) snake_case__ : Union[str, Any] = rearrange(__magic_name__ , """d -> d 1 1""" ) snake_case__ : Any = rearrange(__magic_name__ , """b c h w -> b c 1 h w""" ) snake_case__ : List[str] = ((x & mask) != 0).float() snake_case__ : Optional[int] = rearrange(__magic_name__ , """b c d h w -> b (c d) h w""" ) snake_case__ : Any = bits * 2 - 1 return bits def UpperCamelCase__ ( __magic_name__ : Tuple , __magic_name__ : int=BITS ) -> Optional[int]: '''simple docstring''' snake_case__ : Optional[int] = x.device snake_case__ : str = (x > 0).int() snake_case__ : Union[str, Any] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__magic_name__ , dtype=torch.intaa ) snake_case__ : int = rearrange(__magic_name__ , """d -> d 1 1""" ) snake_case__ : Tuple = rearrange(__magic_name__ , """b (c d) h w -> b c d h w""" , d=8 ) snake_case__ : List[Any] = reduce(x * mask , """b c d h w -> b c h w""" , """sum""" ) return (dec / 2_55).clamp(0.0 , 1.0 ) def UpperCamelCase__ ( self : Dict , __magic_name__ : torch.FloatTensor , __magic_name__ : int , __magic_name__ : torch.FloatTensor , __magic_name__ : float = 0.0 , __magic_name__ : bool = True , __magic_name__ : str=None , __magic_name__ : bool = True , ) -> Union[DDIMSchedulerOutput, Tuple]: '''simple docstring''' if self.num_inference_steps is None: raise ValueError( """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler""" ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) snake_case__ : List[Any] = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas snake_case__ : Union[str, Any] = self.alphas_cumprod[timestep] snake_case__ : Tuple = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod snake_case__ : List[str] = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf snake_case__ : str = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" snake_case__ : Dict = self.bit_scale if self.config.clip_sample: snake_case__ : Any = torch.clamp(__magic_name__ , -scale , __magic_name__ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) snake_case__ : Any = self._get_variance(__magic_name__ , __magic_name__ ) snake_case__ : Optional[Any] = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide snake_case__ : int = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf snake_case__ : str = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf snake_case__ : List[str] = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 snake_case__ : str = model_output.device if torch.is_tensor(__magic_name__ ) else """cpu""" snake_case__ : Union[str, Any] = torch.randn(model_output.shape , dtype=model_output.dtype , generator=__magic_name__ ).to(__magic_name__ ) snake_case__ : int = self._get_variance(__magic_name__ , __magic_name__ ) ** 0.5 * eta * noise snake_case__ : List[Any] = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=__magic_name__ , pred_original_sample=__magic_name__ ) def UpperCamelCase__ ( self : str , __magic_name__ : torch.FloatTensor , __magic_name__ : int , __magic_name__ : torch.FloatTensor , __magic_name__ : Any="epsilon" , __magic_name__ : List[str]=None , __magic_name__ : bool = True , ) -> Union[DDPMSchedulerOutput, Tuple]: '''simple docstring''' snake_case__ : List[str] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: snake_case__ , snake_case__ : List[str] = torch.split(__magic_name__ , sample.shape[1] , dim=1 ) else: snake_case__ : Dict = None # 1. compute alphas, betas snake_case__ : List[Any] = self.alphas_cumprod[t] snake_case__ : List[str] = self.alphas_cumprod[t - 1] if t > 0 else self.one snake_case__ : Union[str, Any] = 1 - alpha_prod_t snake_case__ : List[Any] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": snake_case__ : List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": snake_case__ : Tuple = model_output else: raise ValueError(f"Unsupported prediction_type {prediction_type}." ) # 3. Clip "predicted x_0" snake_case__ : int = self.bit_scale if self.config.clip_sample: snake_case__ : List[str] = torch.clamp(__magic_name__ , -scale , __magic_name__ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf snake_case__ : int = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t snake_case__ : Dict = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf snake_case__ : List[str] = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise snake_case__ : Tuple = 0 if t > 0: snake_case__ : Optional[int] = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=__magic_name__ ).to(model_output.device ) snake_case__ : Tuple = (self._get_variance(__magic_name__ , predicted_variance=__magic_name__ ) ** 0.5) * noise snake_case__ : Optional[Any] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=__magic_name__ , pred_original_sample=__magic_name__ ) class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 1.0 , ): super().__init__() snake_case__ : List[str] = bit_scale snake_case__ : Optional[int] = ( ddim_bit_scheduler_step if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) else ddpm_bit_scheduler_step ) self.register_modules(unet=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , __SCREAMING_SNAKE_CASE = 2_5_6 , __SCREAMING_SNAKE_CASE = 2_5_6 , __SCREAMING_SNAKE_CASE = 5_0 , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = 1 , __SCREAMING_SNAKE_CASE = "pil" , __SCREAMING_SNAKE_CASE = True , **__SCREAMING_SNAKE_CASE , ): snake_case__ : Tuple = torch.randn( (batch_size, self.unet.config.in_channels, height, width) , generator=__SCREAMING_SNAKE_CASE , ) snake_case__ : Dict = decimal_to_bits(__SCREAMING_SNAKE_CASE ) * self.bit_scale snake_case__ : Tuple = latents.to(self.device ) self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE ) for t in self.progress_bar(self.scheduler.timesteps ): # predict the noise residual snake_case__ : str = self.unet(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case__ : List[Any] = self.scheduler.step(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ).prev_sample snake_case__ : int = bits_to_decimal(__SCREAMING_SNAKE_CASE ) if output_type == "pil": snake_case__ : Any = self.numpy_to_pil(__SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=__SCREAMING_SNAKE_CASE )
38
'''simple docstring''' import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class __snake_case : '''simple docstring''' def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=1_6 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=[0, 1, 2, 3] , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_7 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=[1, 3_8_4, 2_4, 2_4] , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=None , ): snake_case__ : str = parent snake_case__ : Union[str, Any] = batch_size snake_case__ : Union[str, Any] = image_size snake_case__ : Optional[int] = patch_size snake_case__ : List[str] = num_channels snake_case__ : Any = is_training snake_case__ : int = use_labels snake_case__ : str = hidden_size snake_case__ : Tuple = num_hidden_layers snake_case__ : str = backbone_out_indices snake_case__ : List[Any] = num_attention_heads snake_case__ : Dict = intermediate_size snake_case__ : Optional[Any] = hidden_act snake_case__ : str = hidden_dropout_prob snake_case__ : int = attention_probs_dropout_prob snake_case__ : Dict = initializer_range snake_case__ : Optional[int] = num_labels snake_case__ : str = backbone_featmap_shape snake_case__ : List[Any] = scope snake_case__ : Optional[Any] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) snake_case__ : List[Any] = (image_size // patch_size) ** 2 snake_case__ : Union[str, Any] = num_patches + 1 def __UpperCamelCase ( self ): snake_case__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : str = None if self.use_labels: snake_case__ : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case__ : Union[str, Any] = self.get_config() return config, pixel_values, labels def __UpperCamelCase ( self ): snake_case__ : Any = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, """hidden_sizes""": [9_6, 1_9_2, 3_8_4, 7_6_8], """num_groups""": 2, } return DPTConfig( 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 , backbone_out_indices=self.backbone_out_indices , 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=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=__SCREAMING_SNAKE_CASE , backbone_featmap_shape=self.backbone_featmap_shape , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Dict = DPTModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Union[str, Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Optional[Any] = self.num_labels snake_case__ : str = DPTForDepthEstimation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : Optional[Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): snake_case__ : Any = self.num_labels snake_case__ : Dict = DPTForSemanticSegmentation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() snake_case__ : str = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __UpperCamelCase ( self ): snake_case__ : Union[str, Any] = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Optional[int] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () lowerCamelCase__ = ( { '''depth-estimation''': DPTForDepthEstimation, '''feature-extraction''': DPTModel, '''image-segmentation''': DPTForSemanticSegmentation, } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def __UpperCamelCase ( self ): snake_case__ : List[Any] = DPTModelTester(self ) snake_case__ : Any = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 ) def __UpperCamelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""DPT does not use inputs_embeds""" ) def __UpperCamelCase ( self ): pass def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Tuple = model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) snake_case__ : str = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def __UpperCamelCase ( self ): snake_case__ , snake_case__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : str = model_class(__SCREAMING_SNAKE_CASE ) snake_case__ : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : List[str] = [*signature.parameters.keys()] snake_case__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): snake_case__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : int = True if model_class in get_values(__SCREAMING_SNAKE_CASE ): continue snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.train() snake_case__ : Optional[Any] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCamelCase ( self ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Union[str, Any] = False snake_case__ : str = True if model_class in get_values(__SCREAMING_SNAKE_CASE ) or not model_class.supports_gradient_checkpointing: continue snake_case__ : Any = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.train() snake_case__ : List[str] = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def __UpperCamelCase ( self ): snake_case__ , snake_case__ : str = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : str = _config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: snake_case__ : Any = model_class(config=__SCREAMING_SNAKE_CASE ) # Skip the check for the backbone snake_case__ : str = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": snake_case__ : Optional[int] = [f"{name}.{key}" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def __UpperCamelCase ( self ): pass @slow def __UpperCamelCase ( self ): for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: snake_case__ : List[str] = DPTModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def __UpperCamelCase ( self ): # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : Dict = """add""" with self.assertRaises(__SCREAMING_SNAKE_CASE ): snake_case__ : List[str] = DPTForDepthEstimation(__SCREAMING_SNAKE_CASE ) def UpperCamelCase__ ( ) -> Dict: '''simple docstring''' snake_case__ : List[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision @slow class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): snake_case__ : Dict = DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" ) snake_case__ : Union[str, Any] = DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = prepare_img() snake_case__ : Optional[int] = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors="""pt""" ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): snake_case__ : Dict = model(**__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = outputs.predicted_depth # verify the predicted depth snake_case__ : Any = torch.Size((1, 3_8_4, 3_8_4) ) self.assertEqual(predicted_depth.shape , __SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0 , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
38
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel 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, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __snake_case ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = CycleDiffusionPipeline lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''negative_prompt''', '''height''', '''width''', '''negative_prompt_embeds''', } lowerCamelCase__ = PipelineTesterMixin.required_optional_params - {'''latents'''} lowerCamelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''} ) lowerCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowerCamelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __UpperCamelCase ( self ): torch.manual_seed(0 ) snake_case__ : Tuple = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=3_2 , ) snake_case__ : List[str] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , num_train_timesteps=1_0_0_0 , clip_sample=__SCREAMING_SNAKE_CASE , set_alpha_to_one=__SCREAMING_SNAKE_CASE , ) torch.manual_seed(0 ) snake_case__ : List[Any] = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case__ : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) snake_case__ : Any = CLIPTextModel(__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) snake_case__ : List[Any] = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ): snake_case__ : List[str] = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(__SCREAMING_SNAKE_CASE ) ).to(__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = image / 2 + 0.5 if str(__SCREAMING_SNAKE_CASE ).startswith("""mps""" ): snake_case__ : Union[str, Any] = torch.manual_seed(__SCREAMING_SNAKE_CASE ) else: snake_case__ : int = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = { """prompt""": """An astronaut riding an elephant""", """source_prompt""": """An astronaut riding a horse""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """eta""": 0.1, """strength""": 0.8, """guidance_scale""": 3, """source_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def __UpperCamelCase ( self ): snake_case__ : Tuple = """cpu""" # ensure determinism for the device-dependent torch.Generator snake_case__ : Union[str, Any] = self.get_dummy_components() snake_case__ : int = CycleDiffusionPipeline(**__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[Any] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) snake_case__ : Any = pipe(**__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = output.images snake_case__ : Dict = images[0, -3:, -3:, -1] assert images.shape == (1, 3_2, 3_2, 3) snake_case__ : Optional[int] = np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def __UpperCamelCase ( self ): snake_case__ : str = self.get_dummy_components() for name, module in components.items(): if hasattr(__SCREAMING_SNAKE_CASE , """half""" ): snake_case__ : Dict = module.half() snake_case__ : Any = CycleDiffusionPipeline(**__SCREAMING_SNAKE_CASE ) snake_case__ : List[Any] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case__ : Tuple = self.get_dummy_inputs(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] = pipe(**__SCREAMING_SNAKE_CASE ) snake_case__ : int = output.images snake_case__ : Dict = images[0, -3:, -3:, -1] assert images.shape == (1, 3_2, 3_2, 3) snake_case__ : Tuple = np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def __UpperCamelCase ( self ): return super().test_save_load_local() @unittest.skip("""non-deterministic pipeline""" ) def __UpperCamelCase ( self ): return super().test_inference_batch_single_identical() @skip_mps def __UpperCamelCase ( self ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def __UpperCamelCase ( self ): return super().test_save_load_optional_components() @skip_mps def __UpperCamelCase ( self ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self ): snake_case__ : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) snake_case__ : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy""" ) snake_case__ : Dict = init_image.resize((5_1_2, 5_1_2) ) snake_case__ : Tuple = """CompVis/stable-diffusion-v1-4""" snake_case__ : Any = DDIMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) snake_case__ : Optional[Any] = CycleDiffusionPipeline.from_pretrained( __SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , torch_dtype=torch.floataa , revision="""fp16""" ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() snake_case__ : Optional[int] = """A black colored car""" snake_case__ : int = """A blue colored car""" snake_case__ : Optional[Any] = torch.manual_seed(0 ) snake_case__ : Any = pipe( prompt=__SCREAMING_SNAKE_CASE , source_prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , num_inference_steps=1_0_0 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) snake_case__ : List[Any] = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5e-1 def __UpperCamelCase ( self ): snake_case__ : Optional[int] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) snake_case__ : Dict = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy""" ) snake_case__ : Any = init_image.resize((5_1_2, 5_1_2) ) snake_case__ : List[str] = """CompVis/stable-diffusion-v1-4""" snake_case__ : Dict = DDIMScheduler.from_pretrained(__SCREAMING_SNAKE_CASE , subfolder="""scheduler""" ) snake_case__ : Dict = CycleDiffusionPipeline.from_pretrained(__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE ) pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) pipe.enable_attention_slicing() snake_case__ : Tuple = """A black colored car""" snake_case__ : List[str] = """A blue colored car""" snake_case__ : Tuple = torch.manual_seed(0 ) snake_case__ : List[str] = pipe( prompt=__SCREAMING_SNAKE_CASE , source_prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , num_inference_steps=1_0_0 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) snake_case__ : int = output.images assert np.abs(image - expected_image ).max() < 2e-2
38
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def UpperCamelCase__ ( __magic_name__ : Optional[Any] ) -> Dict: '''simple docstring''' snake_case__ : int = botoa.client("""iam""" ) snake_case__ : Union[str, Any] = { """Version""": """2012-10-17""", """Statement""": [ {"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=__magic_name__ , AssumeRolePolicyDocument=json.dumps(__magic_name__ , indent=2 ) ) snake_case__ : Dict = { """Version""": """2012-10-17""", """Statement""": [ { """Effect""": """Allow""", """Action""": [ """sagemaker:*""", """ecr:GetDownloadUrlForLayer""", """ecr:BatchGetImage""", """ecr:BatchCheckLayerAvailability""", """ecr:GetAuthorizationToken""", """cloudwatch:PutMetricData""", """cloudwatch:GetMetricData""", """cloudwatch:GetMetricStatistics""", """cloudwatch:ListMetrics""", """logs:CreateLogGroup""", """logs:CreateLogStream""", """logs:DescribeLogStreams""", """logs:PutLogEvents""", """logs:GetLogEvents""", """s3:CreateBucket""", """s3:ListBucket""", """s3:GetBucketLocation""", """s3:GetObject""", """s3:PutObject""", ], """Resource""": """*""", } ], } # attach policy to role iam_client.put_role_policy( RoleName=__magic_name__ , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(__magic_name__ , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def UpperCamelCase__ ( __magic_name__ : Any ) -> Tuple: '''simple docstring''' snake_case__ : List[str] = botoa.client("""iam""" ) return iam_client.get_role(RoleName=__magic_name__ )["Role"]["Arn"] def UpperCamelCase__ ( ) -> Tuple: '''simple docstring''' snake_case__ : Union[str, Any] = _ask_options( """How do you want to authorize?""" , ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """] , __magic_name__ , ) snake_case__ : List[Any] = None if credentials_configuration == 0: snake_case__ : Dict = _ask_field("""Enter your AWS Profile name: [default] """ , default="""default""" ) snake_case__ : List[str] = aws_profile else: print( """Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,""" """`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" ) snake_case__ : List[str] = _ask_field("""AWS Access Key ID: """ ) snake_case__ : int = aws_access_key_id snake_case__ : Optional[Any] = _ask_field("""AWS Secret Access Key: """ ) snake_case__ : List[str] = aws_secret_access_key snake_case__ : Tuple = _ask_field("""Enter your AWS Region: [us-east-1]""" , default="""us-east-1""" ) snake_case__ : Optional[int] = aws_region snake_case__ : int = _ask_options( """Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""" , ["""Provide IAM Role name""", """Create new IAM role using credentials"""] , __magic_name__ , ) if role_management == 0: snake_case__ : Optional[Any] = _ask_field("""Enter your IAM role name: """ ) else: snake_case__ : Optional[int] = """accelerate_sagemaker_execution_role""" print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(__magic_name__ ) snake_case__ : Dict = _ask_field( """Do you want to use custom Docker image? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Any = None if is_custom_docker_image: snake_case__ : str = _ask_field("""Enter your Docker image: """ , lambda __magic_name__ : str(__magic_name__ ).lower() ) snake_case__ : Tuple = _ask_field( """Do you want to provide SageMaker input channels with data locations? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : List[Any] = None if is_sagemaker_inputs_enabled: snake_case__ : str = _ask_field( """Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Optional[int] = _ask_field( """Do you want to enable SageMaker metrics? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Optional[Any] = None if is_sagemaker_metrics_enabled: snake_case__ : List[Any] = _ask_field( """Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """ , lambda __magic_name__ : str(__magic_name__ ).lower() , ) snake_case__ : Tuple = _ask_options( """What is the distributed mode?""" , ["""No distributed training""", """Data parallelism"""] , _convert_sagemaker_distributed_mode , ) snake_case__ : Any = {} snake_case__ : List[Any] = _ask_field( """Do you wish to optimize your script with torch dynamo?[yes/NO]:""" , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_dynamo: snake_case__ : str = """dynamo_""" snake_case__ : Tuple = _ask_options( """Which dynamo backend would you like to use?""" , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) snake_case__ : List[str] = _ask_field( """Do you want to customize the defaults sent to torch.compile? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) if use_custom_options: snake_case__ : str = _ask_options( """Which mode do you want to use?""" , __magic_name__ , lambda __magic_name__ : TORCH_DYNAMO_MODES[int(__magic_name__ )] , default="""default""" , ) snake_case__ : Union[str, Any] = _ask_field( """Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : str = _ask_field( """Do you want to enable dynamic shape tracing? [yes/NO]: """ , _convert_yes_no_to_bool , default=__magic_name__ , error_message="""Please enter yes or no.""" , ) snake_case__ : Dict = """Which EC2 instance type you want to use for your training?""" if distributed_type != SageMakerDistributedType.NO: snake_case__ : List[str] = _ask_options( __magic_name__ , __magic_name__ , lambda __magic_name__ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(__magic_name__ )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" snake_case__ : Optional[int] = _ask_field(__magic_name__ , lambda __magic_name__ : str(__magic_name__ ).lower() , default="""ml.p3.2xlarge""" ) snake_case__ : Dict = 1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): snake_case__ : Optional[Any] = _ask_field( """How many machines do you want use? [1]: """ , __magic_name__ , default=1 , ) snake_case__ : Union[str, Any] = _ask_options( """Do you wish to use FP16 or BF16 (mixed precision)?""" , ["""no""", """fp16""", """bf16""", """fp8"""] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( """Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" ) return SageMakerConfig( image_uri=__magic_name__ , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=__magic_name__ , use_cpu=__magic_name__ , dynamo_config=__magic_name__ , eca_instance_type=__magic_name__ , profile=__magic_name__ , region=__magic_name__ , iam_role_name=__magic_name__ , mixed_precision=__magic_name__ , num_machines=__magic_name__ , sagemaker_inputs_file=__magic_name__ , sagemaker_metrics_file=__magic_name__ , )
38
1