code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries import numpy as np from matplotlib import pyplot as plt from sklearn import datasets def a ( _UpperCAmelCase ) -> List[Any]: """simple docstring""" return 1 / (1 + np.exp(-z )) def a ( _UpperCAmelCase , _UpperCAmelCase ) -> Any: """simple docstring""" return (-y * np.log(UpperCamelCase__ ) - (1 - y) * np.log(1 - h )).mean() def a ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> str: """simple docstring""" a_ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) return np.sum(y * scores - np.log(1 + np.exp(UpperCamelCase__ ) ) ) def a ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=7_0_0_0_0 ) -> Any: """simple docstring""" a_ = np.zeros(x.shape[1] ) for iterations in range(UpperCamelCase__ ): a_ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) a_ = sigmoid_function(UpperCamelCase__ ) a_ = np.dot(x.T , h - y ) / y.size a_ = theta - alpha * gradient # updating the weights a_ = np.dot(UpperCamelCase__ , UpperCamelCase__ ) a_ = sigmoid_function(UpperCamelCase__ ) a_ = cost_function(UpperCamelCase__ , UpperCamelCase__ ) if iterations % 1_0_0 == 0: print(F'''loss: {j} \t''' ) # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": __lowerCAmelCase =datasets.load_iris() __lowerCAmelCase =iris.data[:, :2] __lowerCAmelCase =(iris.target != 0) * 1 __lowerCAmelCase =0.1 __lowerCAmelCase =logistic_reg(alpha, x, y, max_iterations=7_0000) print("theta: ", theta) # printing the theta i.e our weights vector def a ( _UpperCAmelCase ) -> Any: """simple docstring""" return sigmoid_function( np.dot(UpperCamelCase__ , UpperCamelCase__ ) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="b", label="0") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="r", label="1") ((__lowerCAmelCase) , (__lowerCAmelCase)) =(x[:, 0].min(), x[:, 0].max()) ((__lowerCAmelCase) , (__lowerCAmelCase)) =(x[:, 1].min(), x[:, 1].max()) ((__lowerCAmelCase) , (__lowerCAmelCase)) =np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max)) __lowerCAmelCase =np.c_[xxa.ravel(), xxa.ravel()] __lowerCAmelCase =predict_prob(grid).reshape(xxa.shape) plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
697
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = model.config SCREAMING_SNAKE_CASE__ = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) SCREAMING_SNAKE_CASE__ = MBartConfig( is_decoder=UpperCamelCase__ , is_encoder_decoder=UpperCamelCase__ , add_cross_attention=UpperCamelCase__ , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=UpperCamelCase__ , add_final_layer_norm=UpperCamelCase__ , ) return encoder_config, decoder_config def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): if "encoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.model""" , """encoder""" ) if "decoder.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""decoder.model""" , """decoder""" ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if name.startswith("""encoder""" ): if "layers" in name: SCREAMING_SNAKE_CASE__ = """encoder.""" + name if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name and "mask" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.weight""" if name == "encoder.norm.bias": SCREAMING_SNAKE_CASE__ = """encoder.layernorm.bias""" return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = orig_state_dict.pop(UpperCamelCase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_split[3] ) SCREAMING_SNAKE_CASE__ = int(key_split[5] ) SCREAMING_SNAKE_CASE__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: SCREAMING_SNAKE_CASE__ = val[:dim, :] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ = val[-dim:, :] else: SCREAMING_SNAKE_CASE__ = val[:dim] SCREAMING_SNAKE_CASE__ = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: SCREAMING_SNAKE_CASE__ = val return orig_state_dict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: int=None , UpperCamelCase__: str=False ): # load original model SCREAMING_SNAKE_CASE__ = DonutModel.from_pretrained(UpperCamelCase__ ).eval() # load HuggingFace model SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_configs(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutSwinModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = MBartForCausalLM(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = VisionEncoderDecoderModel(encoder=UpperCamelCase__ , decoder=UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ = original_model.state_dict() SCREAMING_SNAKE_CASE__ = convert_state_dict(UpperCamelCase__ , UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # verify results on scanned document SCREAMING_SNAKE_CASE__ = load_dataset("""hf-internal-testing/example-documents""" ) SCREAMING_SNAKE_CASE__ = dataset["""test"""][0]["""image"""].convert("""RGB""" ) SCREAMING_SNAKE_CASE__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase__ , from_slow=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) SCREAMING_SNAKE_CASE__ = DonutProcessor(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = processor(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": SCREAMING_SNAKE_CASE__ = """<s_docvqa><s_question>{user_input}</s_question><s_answer>""" SCREAMING_SNAKE_CASE__ = """When is the coffee break?""" SCREAMING_SNAKE_CASE__ = task_prompt.replace("""{user_input}""" , UpperCamelCase__ ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": SCREAMING_SNAKE_CASE__ = """<s_rvlcdip>""" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: SCREAMING_SNAKE_CASE__ = """<s_cord>""" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": SCREAMING_SNAKE_CASE__ = """s_cord-v2>""" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": SCREAMING_SNAKE_CASE__ = """<s_zhtrainticket>""" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt SCREAMING_SNAKE_CASE__ = """hello world""" else: raise ValueError("""Model name not supported""" ) SCREAMING_SNAKE_CASE__ = original_model.decoder.tokenizer(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors="""pt""" )[ """input_ids""" ] SCREAMING_SNAKE_CASE__ = original_model.encoder.model.patch_embed(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.encoder.embeddings(UpperCamelCase__ ) assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) # verify encoder hidden states SCREAMING_SNAKE_CASE__ = original_model.encoder(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = model.encoder(UpperCamelCase__ ).last_hidden_state assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-2 ) # verify decoder hidden states SCREAMING_SNAKE_CASE__ = original_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).logits SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , decoder_input_ids=UpperCamelCase__ ).logits assert torch.allclose(UpperCamelCase__ , UpperCamelCase__ , atol=1e-3 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: model.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) processor.push_to_hub("""nielsr/""" + model_name.split("""/""" )[-1] , commit_message="""Update model""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='naver-clova-ix/donut-base-finetuned-docvqa', required=False, type=str, help='Name of the original model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, required=False, type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model and processor to the 🤗 hub.', ) _lowerCamelCase = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
6
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available a_ : Union[str, Any] = { '''configuration_gpt_neo''': ['''GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoConfig''', '''GPTNeoOnnxConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : str = [ '''GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoForCausalLM''', '''GPTNeoForQuestionAnswering''', '''GPTNeoForSequenceClassification''', '''GPTNeoForTokenClassification''', '''GPTNeoModel''', '''GPTNeoPreTrainedModel''', '''load_tf_weights_in_gpt_neo''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[int] = [ '''FlaxGPTNeoForCausalLM''', '''FlaxGPTNeoModel''', '''FlaxGPTNeoPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys a_ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
263
"""simple docstring""" import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 a_ : Optional[int] = { '''return_dict''': False, '''output_hidden_states''': True, '''output_attentions''': True, '''torchscript''': True, '''torch_dtype''': '''float16''', '''use_bfloat16''': True, '''tf_legacy_loss''': True, '''pruned_heads''': {'''a''': 1}, '''tie_word_embeddings''': False, '''is_decoder''': True, '''cross_attention_hidden_size''': 1_28, '''add_cross_attention''': True, '''tie_encoder_decoder''': True, '''max_length''': 50, '''min_length''': 3, '''do_sample''': True, '''early_stopping''': True, '''num_beams''': 3, '''num_beam_groups''': 3, '''diversity_penalty''': 0.5, '''temperature''': 2.0, '''top_k''': 10, '''top_p''': 0.7, '''typical_p''': 0.2, '''repetition_penalty''': 0.8, '''length_penalty''': 0.8, '''no_repeat_ngram_size''': 5, '''encoder_no_repeat_ngram_size''': 5, '''bad_words_ids''': [1, 2, 3], '''num_return_sequences''': 3, '''chunk_size_feed_forward''': 5, '''output_scores''': True, '''return_dict_in_generate''': True, '''forced_bos_token_id''': 2, '''forced_eos_token_id''': 3, '''remove_invalid_values''': True, '''architectures''': ['''BertModel'''], '''finetuning_task''': '''translation''', '''id2label''': {0: '''label'''}, '''label2id''': {'''label''': '''0'''}, '''tokenizer_class''': '''BertTokenizerFast''', '''prefix''': '''prefix''', '''bos_token_id''': 6, '''pad_token_id''': 7, '''eos_token_id''': 8, '''sep_token_id''': 9, '''decoder_start_token_id''': 10, '''exponential_decay_length_penalty''': (5, 1.0_1), '''suppress_tokens''': [0, 1], '''begin_suppress_tokens''': 2, '''task_specific_params''': {'''translation''': '''some_params'''}, '''problem_type''': '''regression''', } @is_staging_test class __lowercase( unittest.TestCase ): '''simple docstring''' @classmethod def snake_case_ ( cls ): __lowerCamelCase : Tuple = TOKEN HfFolder.save_token(__a ) @classmethod def snake_case_ ( cls ): try: delete_repo(token=cls._token , repo_id='test-config' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-config-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-config' ) except HTTPError: pass def snake_case_ ( self ): __lowerCamelCase : List[str] = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('test-config' , use_auth_token=self._token ) __lowerCamelCase : Any = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__a , getattr(__a , __a ) ) # Reset repo delete_repo(token=self._token , repo_id='test-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(__a , repo_id='test-config' , push_to_hub=__a , use_auth_token=self._token ) __lowerCamelCase : Any = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__a , getattr(__a , __a ) ) def snake_case_ ( self ): __lowerCamelCase : int = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) config.push_to_hub('valid_org/test-config-org' , use_auth_token=self._token ) __lowerCamelCase : Tuple = BertConfig.from_pretrained('valid_org/test-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__a , getattr(__a , __a ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( __a , repo_id='valid_org/test-config-org' , push_to_hub=__a , use_auth_token=self._token ) __lowerCamelCase : Tuple = BertConfig.from_pretrained('valid_org/test-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(__a , getattr(__a , __a ) ) def snake_case_ ( self ): CustomConfig.register_for_auto_class() __lowerCamelCase : Optional[Any] = CustomConfig(attribute=42 ) config.push_to_hub('test-dynamic-config' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {'AutoConfig': 'custom_configuration.CustomConfig'} ) __lowerCamelCase : Tuple = AutoConfig.from_pretrained(f'''{USER}/test-dynamic-config''' , trust_remote_code=__a ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , 'CustomConfig' ) self.assertEqual(new_config.attribute , 42 ) class __lowercase( unittest.TestCase ): '''simple docstring''' def snake_case_ ( self ): __lowerCamelCase : Tuple = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated __lowerCamelCase : List[str] = c.n_embd + 1 # int __lowerCamelCase : Dict = c.resid_pdrop + 1.0 # float __lowerCamelCase : int = not c.scale_attn_weights # bool __lowerCamelCase : Optional[int] = c.summary_type + 'foo' # str c.update_from_string( f'''n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}''' ) self.assertEqual(__a , c.n_embd , 'mismatch for key: n_embd' ) self.assertEqual(__a , c.resid_pdrop , 'mismatch for key: resid_pdrop' ) self.assertEqual(__a , c.scale_attn_weights , 'mismatch for key: scale_attn_weights' ) self.assertEqual(__a , c.summary_type , 'mismatch for key: summary_type' ) def snake_case_ ( self ): __lowerCamelCase : Tuple = PretrainedConfig() __lowerCamelCase : Dict = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( __a , ['is_encoder_decoder', '_name_or_path', '_commit_hash', 'transformers_version'] ) __lowerCamelCase : int = [key for key, value in config_common_kwargs.items() if value == getattr(__a , __a )] if len(__a ) > 0: raise ValueError( 'The following keys are set with the default values in' ' `test_configuration_common.config_common_kwargs` pick another value for them:' f''' {", ".join(__a )}.''' ) def snake_case_ ( self ): with self.assertRaises(__a ): # config is in subfolder, the following should not work without specifying the subfolder __lowerCamelCase : int = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder' ) __lowerCamelCase : Optional[int] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder' , subfolder='bert' ) self.assertIsNotNone(__a ) def snake_case_ ( self ): # A mock response for an HTTP head request to emulate server down __lowerCamelCase : List[str] = mock.Mock() __lowerCamelCase : Tuple = 500 __lowerCamelCase : Tuple = {} __lowerCamelCase : Optional[Any] = HTTPError __lowerCamelCase : str = {} # Download this model to make sure it's in the cache. __lowerCamelCase : Optional[int] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=__a ) as mock_head: __lowerCamelCase : Union[str, Any] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() def snake_case_ ( self ): # This test is for deprecated behavior and can be removed in v5 __lowerCamelCase : Optional[Any] = BertConfig.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json' ) def snake_case_ ( self ): __lowerCamelCase : List[Any] = AutoConfig.from_pretrained('bert-base-cased' ) __lowerCamelCase : str = ['config.4.0.0.json'] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(__a ) __lowerCamelCase : Optional[int] = 2 json.dump(configuration.to_dict() , open(os.path.join(__a , 'config.4.0.0.json' ) , 'w' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 __lowerCamelCase : Any = AutoConfig.from_pretrained(__a ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 __lowerCamelCase : Any = ['config.42.0.0.json'] __lowerCamelCase : Tuple = 768 configuration.save_pretrained(__a ) shutil.move(os.path.join(__a , 'config.4.0.0.json' ) , os.path.join(__a , 'config.42.0.0.json' ) ) __lowerCamelCase : Dict = AutoConfig.from_pretrained(__a ) self.assertEqual(new_configuration.hidden_size , 768 ) def snake_case_ ( self ): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. __lowerCamelCase : List[str] = 'hf-internal-testing/test-two-configs' import transformers as new_transformers __lowerCamelCase : Tuple = 'v4.0.0' __lowerCamelCase , __lowerCamelCase : Optional[Any] = new_transformers.models.auto.AutoConfig.from_pretrained( __a , return_unused_kwargs=__a ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(__a , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers __lowerCamelCase : Union[str, Any] = 'v3.0.0' __lowerCamelCase : Optional[int] = old_transformers.models.auto.AutoConfig.from_pretrained(__a ) self.assertEqual(old_configuration.hidden_size , 768 )
263
1
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 __a :Tuple = logging.get_logger(__name__) __a :Tuple = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} __a :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' ), }, } __a :Union[str, Any] = { '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 ( snake_case_ ): """simple docstring""" _lowerCamelCase : Tuple = VOCAB_FILES_NAMES _lowerCamelCase : int = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase : Optional[Any] = ['input_ids', 'attention_mask'] _lowerCamelCase : Tuple = RobertaTokenizer def __init__( self : int , UpperCAmelCase : Union[str, Any]=None , UpperCAmelCase : Union[str, Any]=None , UpperCAmelCase : Any=None , UpperCAmelCase : Optional[Any]="replace" , UpperCAmelCase : Optional[int]="<s>" , UpperCAmelCase : Tuple="</s>" , UpperCAmelCase : Tuple="</s>" , UpperCAmelCase : Optional[Any]="<s>" , UpperCAmelCase : Optional[int]="<unk>" , UpperCAmelCase : Any="<pad>" , UpperCAmelCase : Union[str, Any]="<mask>" , UpperCAmelCase : Optional[Any]=False , UpperCAmelCase : Optional[int]=True , **UpperCAmelCase : Tuple , ): super().__init__( UpperCAmelCase , UpperCAmelCase , tokenizer_file=UpperCAmelCase , errors=UpperCAmelCase , bos_token=UpperCAmelCase , eos_token=UpperCAmelCase , sep_token=UpperCAmelCase , cls_token=UpperCAmelCase , unk_token=UpperCAmelCase , pad_token=UpperCAmelCase , mask_token=UpperCAmelCase , add_prefix_space=UpperCAmelCase , trim_offsets=UpperCAmelCase , **UpperCAmelCase , ) A_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , UpperCAmelCase ) != add_prefix_space: A_ = getattr(UpperCAmelCase , pre_tok_state.pop("type" ) ) A_ = add_prefix_space A_ = pre_tok_class(**UpperCAmelCase ) A_ = add_prefix_space A_ = "post_processor" A_ = getattr(self.backend_tokenizer , UpperCAmelCase , UpperCAmelCase ) if tokenizer_component_instance: A_ = 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(state["sep"] ) if "cls" in state: A_ = tuple(state["cls"] ) A_ = False if state.get("add_prefix_space" , UpperCAmelCase ) != add_prefix_space: A_ = add_prefix_space A_ = True if state.get("trim_offsets" , UpperCAmelCase ) != trim_offsets: A_ = trim_offsets A_ = True if changes_to_apply: A_ = getattr(UpperCAmelCase , state.pop("type" ) ) A_ = component_class(**UpperCAmelCase ) setattr(self.backend_tokenizer , UpperCAmelCase , UpperCAmelCase ) @property def __A ( self : Tuple ): 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 __A ( self : List[Any] , UpperCAmelCase : str ): A_ = AddedToken(UpperCAmelCase , lstrip=UpperCAmelCase , rstrip=UpperCAmelCase ) if isinstance(UpperCAmelCase , UpperCAmelCase ) else value A_ = value def __A ( self : Tuple , *UpperCAmelCase : Tuple , **UpperCAmelCase : List[str] ): A_ = kwargs.get("is_split_into_words" , UpperCAmelCase ) 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(*UpperCAmelCase , **UpperCAmelCase ) def __A ( self : Tuple , *UpperCAmelCase : Dict , **UpperCAmelCase : str ): A_ = kwargs.get("is_split_into_words" , UpperCAmelCase ) 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(*UpperCAmelCase , **UpperCAmelCase ) def __A ( self : Any , UpperCAmelCase : str , UpperCAmelCase : Optional[str] = None ): A_ = self._tokenizer.model.save(UpperCAmelCase , name=UpperCAmelCase ) return tuple(UpperCAmelCase ) def __A ( self : Any , UpperCAmelCase : Optional[int] , UpperCAmelCase : Union[str, Any]=None ): A_ = [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 __A ( self : Optional[int] , UpperCAmelCase : List[int] , UpperCAmelCase : Optional[List[int]] = None ): A_ = [self.sep_token_id] A_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
86
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging lowerCamelCase__ : Any = """\ """ lowerCamelCase__ : List[str] = """ Perplexity (PPL) is one of the most common metrics for evaluating language models. It is defined as the exponentiated average negative log-likelihood of a sequence. For more information, see https://huggingface.co/docs/transformers/perplexity """ lowerCamelCase__ : Any = """ Args: model_id (str): model used for calculating Perplexity NOTE: Perplexity can only be calculated for causal language models. This includes models such as gpt2, causal variations of bert, causal versions of t5, and more (the full list can be found in the AutoModelForCausalLM documentation here: https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM ) input_texts (list of str): input text, each separate text snippet is one list entry. batch_size (int): the batch size to run texts through the model. Defaults to 16. add_start_token (bool): whether to add the start token to the texts, so the perplexity can include the probability of the first word. Defaults to True. device (str): device to run on, defaults to 'cuda' when available Returns: perplexity: dictionary containing the perplexity scores for the texts in the input list, as well as the mean perplexity. If one of the input texts is longer than the max input length of the model, then it is truncated to the max length for the perplexity computation. Examples: Example 1: >>> perplexity = datasets.load_metric(\"perplexity\") >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"] >>> results = perplexity.compute(model_id='gpt2', ... add_start_token=False, ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) ['perplexities', 'mean_perplexity'] >>> print(round(results[\"mean_perplexity\"], 2)) 78.22 >>> print(round(results[\"perplexities\"][0], 2)) 11.11 Example 2: >>> perplexity = datasets.load_metric(\"perplexity\") >>> input_texts = datasets.load_dataset(\"wikitext\", ... \"wikitext-2-raw-v1\", ... split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS [...] >>> input_texts = [s for s in input_texts if s!=''] >>> results = perplexity.compute(model_id='gpt2', ... input_texts=input_texts) # doctest:+ELLIPSIS >>> print(list(results.keys())) ['perplexities', 'mean_perplexity'] >>> print(round(results[\"mean_perplexity\"], 2)) 60.35 >>> print(round(results[\"perplexities\"][0], 2)) 81.12 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class __magic_name__ (datasets.Metric ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self:int ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''input_texts''': datasets.Value('''string''' ), } ) , reference_urls=['''https://huggingface.co/docs/transformers/perplexity'''] , ) def SCREAMING_SNAKE_CASE__ ( self:List[Any] , _a:int , _a:List[Any] , _a:int = 16 , _a:bool = True , _a:Any=None ): if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": snake_case__ = '''cuda''' else: snake_case__ = '''cuda''' if torch.cuda.is_available() else '''cpu''' snake_case__ = AutoModelForCausalLM.from_pretrained(_a ) snake_case__ = model.to(_a ) snake_case__ = AutoTokenizer.from_pretrained(_a ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: snake_case__ = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(_a ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({'''pad_token''': existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" snake_case__ = model.config.max_length - 1 else: snake_case__ = model.config.max_length snake_case__ = tokenizer( _a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , return_tensors='''pt''' , return_attention_mask=_a , ).to(_a ) snake_case__ = encodings['''input_ids'''] snake_case__ = encodings['''attention_mask'''] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) , 1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) , 2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." snake_case__ = [] snake_case__ = CrossEntropyLoss(reduction='''none''' ) for start_index in logging.tqdm(range(0 , len(_a ) , _a ) ): snake_case__ = min(start_index + batch_size , len(_a ) ) snake_case__ = encoded_texts[start_index:end_index] snake_case__ = attn_masks[start_index:end_index] if add_start_token: snake_case__ = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(_a ) snake_case__ = torch.cat([bos_tokens_tensor, encoded_batch] , dim=1 ) snake_case__ = torch.cat( [torch.ones(bos_tokens_tensor.size() , dtype=torch.intaa ).to(_a ), attn_mask] , dim=1 ) snake_case__ = encoded_batch with torch.no_grad(): snake_case__ = model(_a , attention_mask=_a ).logits snake_case__ = out_logits[..., :-1, :].contiguous() snake_case__ = labels[..., 1:].contiguous() snake_case__ = attn_mask[..., 1:].contiguous() snake_case__ = torch.expa( (loss_fct(shift_logits.transpose(1 , 2 ) , _a ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(_a )}
33
0
"""simple docstring""" def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError("multiplicative_persistence() only accepts integral values" ) if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values" ) UpperCamelCase = 0 UpperCamelCase = str(_SCREAMING_SNAKE_CASE ) while len(_SCREAMING_SNAKE_CASE ) != 1: UpperCamelCase = [int(_SCREAMING_SNAKE_CASE ) for i in num_string] UpperCamelCase = 1 for i in range(0 , len(_SCREAMING_SNAKE_CASE ) ): total *= numbers[i] UpperCamelCase = str(_SCREAMING_SNAKE_CASE ) steps += 1 return steps def a__ ( _SCREAMING_SNAKE_CASE ): """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError("additive_persistence() only accepts integral values" ) if num < 0: raise ValueError("additive_persistence() does not accept negative values" ) UpperCamelCase = 0 UpperCamelCase = str(_SCREAMING_SNAKE_CASE ) while len(_SCREAMING_SNAKE_CASE ) != 1: UpperCamelCase = [int(_SCREAMING_SNAKE_CASE ) for i in num_string] UpperCamelCase = 0 for i in range(0 , len(_SCREAMING_SNAKE_CASE ) ): total += numbers[i] UpperCamelCase = str(_SCREAMING_SNAKE_CASE ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
544
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class _lowerCamelCase : pass
544
1
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def UpperCAmelCase_ ( __lowerCamelCase : Optional[Any] ): return np.dot(__lowerCamelCase ,__lowerCamelCase ) class a_ : def __init__( self : int , *, lowercase : float = np.inf , lowercase : str = "linear" , lowercase : float = 0.0 , ): """simple docstring""" lowercase_ :Optional[int] = regularization lowercase_ :int = gamma if kernel == "linear": lowercase_ :Optional[int] = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) lowercase_ :Union[str, Any] = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: lowercase_ :Optional[Any] = F'Unknown kernel: {kernel}' raise ValueError(snake_case__ ) def lowercase__ ( self : Tuple , lowercase : ndarray , lowercase : ndarray ): """simple docstring""" return np.dot(snake_case__ , snake_case__ ) def lowercase__ ( self : int , lowercase : ndarray , lowercase : ndarray ): """simple docstring""" return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def lowercase__ ( self : int , lowercase : list[ndarray] , lowercase : ndarray ): """simple docstring""" lowercase_ :Tuple = observations lowercase_ :Optional[Any] = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((lowercase_ ) , ) :Tuple = np.shape(snake_case__ ) def to_minimize(lowercase : ndarray ) -> float: lowercase_ :List[str] = 0 ((lowercase_ ) , ) :Optional[int] = np.shape(snake_case__ ) for i in range(snake_case__ ): for j in range(snake_case__ ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(snake_case__ ) lowercase_ :List[Any] = LinearConstraint(snake_case__ , 0 , 0 ) lowercase_ :List[str] = Bounds(0 , self.regularization ) lowercase_ :Union[str, Any] = minimize( snake_case__ , np.ones(snake_case__ ) , bounds=snake_case__ , constraints=[ly_contraint] ).x lowercase_ :Optional[Any] = l_star # calculating mean offset of separation plane to points lowercase_ :List[Any] = 0 for i in range(snake_case__ ): for j in range(snake_case__ ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) lowercase_ :List[str] = s / n def lowercase__ ( self : Any , lowercase : ndarray ): """simple docstring""" lowercase_ :Optional[int] = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , snake_case__ ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
172
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params SCREAMING_SNAKE_CASE: Optional[int] = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['''memory_attention''', '''encoder_attn'''], ['''attention''', '''attn'''], ['''/''', '''.'''], ['''.LayerNorm.gamma''', '''_layer_norm.weight'''], ['''.LayerNorm.beta''', '''_layer_norm.bias'''], ['''r.layer_''', '''r.layers.'''], ['''output_proj''', '''out_proj'''], ['''ffn.dense_1.''', '''fc2.'''], ['''ffn.dense.''', '''fc1.'''], ['''ffn_layer_norm''', '''final_layer_norm'''], ['''kernel''', '''weight'''], ['''encoder_layer_norm.''', '''encoder.layer_norm.'''], ['''decoder_layer_norm.''', '''decoder.layer_norm.'''], ['''embeddings.weights''', '''shared.weight'''], ] def _a ( lowerCAmelCase )-> str: for pegasus_name, hf_name in PATTERNS: SCREAMING_SNAKE_CASE_ = k.replace(lowerCAmelCase , lowerCAmelCase ) return k def _a ( lowerCAmelCase , lowerCAmelCase )-> PegasusForConditionalGeneration: SCREAMING_SNAKE_CASE_ = DEFAULTS.copy() cfg_kwargs.update(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = PegasusConfig(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = PegasusForConditionalGeneration(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = torch_model.model.state_dict() SCREAMING_SNAKE_CASE_ = {} for k, v in tf_weights.items(): SCREAMING_SNAKE_CASE_ = rename_state_dict_key(lowerCAmelCase ) if new_k not in sd: raise ValueError(F'''could not find new key {new_k} in state dict. (converted from {k})''' ) if "dense" in k or "proj" in new_k: SCREAMING_SNAKE_CASE_ = v.T SCREAMING_SNAKE_CASE_ = torch.tensor(lowerCAmelCase , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, F'''{new_k}, {k}, {v.shape}, {sd[new_k].shape}''' # make sure embedding.padding_idx is respected SCREAMING_SNAKE_CASE_ = torch.zeros_like(mapping['shared.weight'][cfg.pad_token_id + 1] ) SCREAMING_SNAKE_CASE_ = mapping['shared.weight'] SCREAMING_SNAKE_CASE_ = mapping['shared.weight'] SCREAMING_SNAKE_CASE_ = {k: torch.zeros_like(lowerCAmelCase ) for k, v in sd.items() if k.endswith('bias' ) and k not in mapping} mapping.update(**lowerCAmelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = torch_model.model.load_state_dict(lowerCAmelCase , strict=lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = [ k for k in missing if k not in ['encoder.embed_positions.weight', 'decoder.embed_positions.weight'] ] assert unexpected_missing == [], F'''no matches found for the following torch keys {unexpected_missing}''' assert extra == [], F'''no matches found for the following tf keys {extra}''' return torch_model def _a ( lowerCAmelCase="./ckpt/aeslc/model.ckpt-32000" )-> Dict: SCREAMING_SNAKE_CASE_ = tf.train.list_variables(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = ['Adafactor', 'global_step'] for name, shape in tqdm(lowerCAmelCase , desc='converting tf checkpoint to dict' ): SCREAMING_SNAKE_CASE_ = any(pat in name for pat in ignore_name ) if skip_key: continue SCREAMING_SNAKE_CASE_ = tf.train.load_variable(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = array return tf_weights def _a ( lowerCAmelCase , lowerCAmelCase )-> Optional[Any]: # save tokenizer first SCREAMING_SNAKE_CASE_ = Path(lowerCAmelCase ).parent.name SCREAMING_SNAKE_CASE_ = task_specific_params[F'''summarization_{dataset}''']['max_position_embeddings'] SCREAMING_SNAKE_CASE_ = PegasusTokenizer.from_pretrained('sshleifer/pegasus' , model_max_length=lowerCAmelCase ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(lowerCAmelCase ) # convert model SCREAMING_SNAKE_CASE_ = get_tf_weights_as_numpy(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = task_specific_params[F'''summarization_{dataset}'''] if dataset == "large": SCREAMING_SNAKE_CASE_ = task_specific_params SCREAMING_SNAKE_CASE_ = convert_pegasus(lowerCAmelCase , lowerCAmelCase ) torch_model.save_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = torch_model.state_dict() sd.pop('model.decoder.embed_positions.weight' ) sd.pop('model.encoder.embed_positions.weight' ) torch.save(lowerCAmelCase , Path(lowerCAmelCase ) / 'pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE: Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('''tf_ckpt_path''', type=str, help='''passed to tf.train.list_variables''') parser.add_argument('''save_dir''', default=None, type=str, help='''Path to the output PyTorch model.''') SCREAMING_SNAKE_CASE: int = parser.parse_args() if args.save_dir is None: SCREAMING_SNAKE_CASE: List[Any] = Path(args.tf_ckpt_path).parent.name SCREAMING_SNAKE_CASE: Tuple = os.path.join('''pegasus''', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
360
0
'''simple docstring''' from __future__ import annotations snake_case_ : Optional[int] = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] snake_case_ : Tuple = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def __snake_case ( _UpperCAmelCase : list[float]): UpperCamelCase = [] UpperCamelCase = len(_UpperCAmelCase) for i in range(_UpperCAmelCase): UpperCamelCase = -1 for j in range(i + 1, _UpperCAmelCase): if arr[i] < arr[j]: UpperCamelCase = arr[j] break result.append(_UpperCAmelCase) return result def __snake_case ( _UpperCAmelCase : list[float]): UpperCamelCase = [] for i, outer in enumerate(_UpperCAmelCase): UpperCamelCase = -1 for inner in arr[i + 1 :]: if outer < inner: UpperCamelCase = inner break result.append(_UpperCAmelCase) return result def __snake_case ( _UpperCAmelCase : list[float]): UpperCamelCase = len(_UpperCAmelCase) UpperCamelCase = [] UpperCamelCase = [-1] * arr_size for index in reversed(range(_UpperCAmelCase)): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: UpperCamelCase = stack[-1] stack.append(arr[index]) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) snake_case_ : Dict = ( 'from __main__ import arr, next_greatest_element_slow, ' 'next_greatest_element_fast, next_greatest_element' ) print( 'next_greatest_element_slow():', timeit('next_greatest_element_slow(arr)', setup=setup), ) print( 'next_greatest_element_fast():', timeit('next_greatest_element_fast(arr)', setup=setup), ) print( ' next_greatest_element():', timeit('next_greatest_element(arr)', setup=setup), )
350
'''simple docstring''' from typing import Dict, Iterable, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract snake_case_ : Tuple = logging.get_logger(__name__) def __snake_case ( _UpperCAmelCase : str, _UpperCAmelCase : int, _UpperCAmelCase : Optional[int]): return [ int(1000 * (box[0] / width)), int(1000 * (box[1] / height)), int(1000 * (box[2] / width)), int(1000 * (box[3] / height)), ] def __snake_case ( _UpperCAmelCase : np.ndarray, _UpperCAmelCase : Optional[str], _UpperCAmelCase : Optional[str]): UpperCamelCase = to_pil_image(_UpperCAmelCase) UpperCamelCase , UpperCamelCase = pil_image.size UpperCamelCase = pytesseract.image_to_data(_UpperCAmelCase, lang=_UpperCAmelCase, output_type='''dict''', config=_UpperCAmelCase) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates UpperCamelCase = [idx for idx, word in enumerate(_UpperCAmelCase) if not word.strip()] UpperCamelCase = [word for idx, word in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices] UpperCamelCase = [coord for idx, coord in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices] UpperCamelCase = [coord for idx, coord in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices] UpperCamelCase = [coord for idx, coord in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices] UpperCamelCase = [coord for idx, coord in enumerate(_UpperCAmelCase) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format UpperCamelCase = [] for x, y, w, h in zip(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase): UpperCamelCase = [x, y, x + w, y + h] actual_boxes.append(_UpperCAmelCase) # finally, normalize the bounding boxes UpperCamelCase = [] for box in actual_boxes: normalized_boxes.append(normalize_box(_UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase)) assert len(_UpperCAmelCase) == len(_UpperCAmelCase), "Not as many words as there are bounding boxes" return words, normalized_boxes class lowercase__ ( snake_case_ ): '''simple docstring''' _snake_case = ['''pixel_values'''] def __init__( self , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = PILImageResampling.BILINEAR , lowerCamelCase__ = True , lowerCamelCase__ = 1 / 2_5_5 , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = True , lowerCamelCase__ = None , lowerCamelCase__ = "" , **lowerCamelCase__ , ): '''simple docstring''' super().__init__(**lowerCamelCase__ ) UpperCamelCase = size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4} UpperCamelCase = get_size_dict(lowerCamelCase__ ) UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = resample UpperCamelCase = do_rescale UpperCamelCase = rescale_value UpperCamelCase = do_normalize UpperCamelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN UpperCamelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD UpperCamelCase = apply_ocr UpperCamelCase = ocr_lang UpperCamelCase = tesseract_config def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = PILImageResampling.BILINEAR , lowerCamelCase__ = None , **lowerCamelCase__ , ): '''simple docstring''' UpperCamelCase = get_size_dict(lowerCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f'The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}' ) UpperCamelCase = (size['''height'''], size['''width''']) return resize(lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ ) def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , **lowerCamelCase__ , ): '''simple docstring''' return rescale(lowerCamelCase__ , scale=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ ) def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = None , **lowerCamelCase__ , ): '''simple docstring''' return normalize(lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ ) def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__=None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = None , lowerCamelCase__ = ChannelDimension.FIRST , **lowerCamelCase__ , ): '''simple docstring''' UpperCamelCase = do_resize if do_resize is not None else self.do_resize UpperCamelCase = size if size is not None else self.size UpperCamelCase = get_size_dict(lowerCamelCase__ ) UpperCamelCase = resample if resample is not None else self.resample UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase = image_mean if image_mean is not None else self.image_mean UpperCamelCase = image_std if image_std is not None else self.image_std UpperCamelCase = apply_ocr if apply_ocr is not None else self.apply_ocr UpperCamelCase = ocr_lang if ocr_lang is not None else self.ocr_lang UpperCamelCase = tesseract_config if tesseract_config is not None else self.tesseract_config UpperCamelCase = make_list_of_images(lowerCamelCase__ ) if not valid_images(lowerCamelCase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''If do_normalize is True, image_mean and image_std must be specified.''' ) # All transformations expect numpy arrays. UpperCamelCase = [to_numpy_array(lowerCamelCase__ ) for image in images] # Tesseract OCR to get words + normalized bounding boxes if apply_ocr: requires_backends(self , '''pytesseract''' ) UpperCamelCase = [] UpperCamelCase = [] for image in images: UpperCamelCase , UpperCamelCase = apply_tesseract(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) words_batch.append(lowerCamelCase__ ) boxes_batch.append(lowerCamelCase__ ) if do_resize: UpperCamelCase = [self.resize(image=lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ ) for image in images] if do_rescale: UpperCamelCase = [self.rescale(image=lowerCamelCase__ , scale=lowerCamelCase__ ) for image in images] if do_normalize: UpperCamelCase = [self.normalize(image=lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ ) for image in images] UpperCamelCase = [to_channel_dimension_format(lowerCamelCase__ , lowerCamelCase__ ) for image in images] UpperCamelCase = BatchFeature(data={'''pixel_values''': images} , tensor_type=lowerCamelCase__ ) if apply_ocr: UpperCamelCase = words_batch UpperCamelCase = boxes_batch return data
350
1
import re from filelock import FileLock try: import nltk UpperCamelCase = True except (ImportError, ModuleNotFoundError): UpperCamelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def _A ( lowerCAmelCase_ : str ): """simple docstring""" re.sub("<n>" , "" , lowerCAmelCase_ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(lowerCAmelCase_ ) )
61
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
1
'''simple docstring''' import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class lowerCamelCase_ : def __init__( self : Dict , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any]=13 , lowerCAmelCase__ : Any=10 , lowerCAmelCase__ : Tuple=3 , lowerCAmelCase__ : str=2 , lowerCAmelCase__ : Any=2 , lowerCAmelCase__ : Any=True , lowerCAmelCase__ : List[str]=True , lowerCAmelCase__ : Any=32 , lowerCAmelCase__ : Dict=5 , lowerCAmelCase__ : Any=4 , lowerCAmelCase__ : Any=37 , lowerCAmelCase__ : Optional[Any]="gelu" , lowerCAmelCase__ : Optional[int]=0.1 , lowerCAmelCase__ : Tuple=0.1 , lowerCAmelCase__ : Union[str, Any]=10 , lowerCAmelCase__ : Union[str, Any]=0.02 , lowerCAmelCase__ : Any="divided_space_time" , lowerCAmelCase__ : Union[str, Any]=None , ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Optional[int] = image_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : Dict = num_frames SCREAMING_SNAKE_CASE : Tuple = is_training SCREAMING_SNAKE_CASE : str = use_labels SCREAMING_SNAKE_CASE : str = hidden_size SCREAMING_SNAKE_CASE : Dict = num_hidden_layers SCREAMING_SNAKE_CASE : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE : List[str] = hidden_act SCREAMING_SNAKE_CASE : int = hidden_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = attention_type SCREAMING_SNAKE_CASE : Any = initializer_range SCREAMING_SNAKE_CASE : str = scope SCREAMING_SNAKE_CASE : Optional[Any] = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token SCREAMING_SNAKE_CASE : Optional[Any] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE : List[Any] = (num_frames) * self.num_patches_per_frame + 1 def __lowercase ( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : str = None if self.use_labels: SCREAMING_SNAKE_CASE : List[str] = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, pixel_values, labels def __lowercase ( self : List[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , 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 , initializer_range=self.initializer_range , attention_type=self.attention_type , ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels return config def __lowercase ( self : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = TimesformerModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : int = TimesformerForVideoClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(__lowerCAmelCase ) # verify the logits shape SCREAMING_SNAKE_CASE : Optional[int] = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , __lowerCAmelCase ) def __lowercase ( self : str ): """simple docstring""" SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE : List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): _lowerCAmelCase : Optional[int] = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () _lowerCAmelCase : Optional[int] = ( {'feature-extraction': TimesformerModel, 'video-classification': TimesformerForVideoClassification} if is_torch_available() else {} ) _lowerCAmelCase : str = False _lowerCAmelCase : Any = False _lowerCAmelCase : Union[str, Any] = False _lowerCAmelCase : List[Any] = False def __lowercase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : str = TimesformerModelTester(self ) SCREAMING_SNAKE_CASE : List[Any] = ConfigTester( self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=37 ) def __lowercase ( self : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any]=False ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = copy.deepcopy(__lowerCAmelCase ) if return_labels: if model_class in get_values(__lowerCAmelCase ): SCREAMING_SNAKE_CASE : Any = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCAmelCase ) return inputs_dict def __lowercase ( self : List[Any] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''TimeSformer does not use inputs_embeds''' ) def __lowercase ( self : int ): """simple docstring""" pass def __lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Any = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE : Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def __lowercase ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[int] = model_class(__lowerCAmelCase ) SCREAMING_SNAKE_CASE : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def __lowercase ( self : Any ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def __lowercase ( self : Union[str, Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*__lowerCAmelCase ) @slow def __lowercase ( self : Dict ): """simple docstring""" for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : List[str] = TimesformerModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def __lowercase ( self : Optional[int] ): """simple docstring""" if not self.has_attentions: pass else: SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE : List[Any] = True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.seq_length SCREAMING_SNAKE_CASE : Dict = self.model_tester.num_frames SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Dict = False SCREAMING_SNAKE_CASE : Any = True SCREAMING_SNAKE_CASE : Union[str, Any] = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : int = model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) ) SCREAMING_SNAKE_CASE : Optional[int] = outputs.attentions self.assertEqual(len(__lowerCAmelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE : Union[str, Any] = True SCREAMING_SNAKE_CASE : int = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : Any = model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) ) SCREAMING_SNAKE_CASE : Optional[int] = outputs.attentions self.assertEqual(len(__lowerCAmelCase ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) SCREAMING_SNAKE_CASE : Union[str, Any] = len(__lowerCAmelCase ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : str = True SCREAMING_SNAKE_CASE : Dict = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[int] = model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) ) self.assertEqual(out_len + 1 , len(__lowerCAmelCase ) ) SCREAMING_SNAKE_CASE : Optional[int] = outputs.attentions self.assertEqual(len(__lowerCAmelCase ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def __lowercase ( self : Optional[int] ): """simple docstring""" def check_hidden_states_output(lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : str ): SCREAMING_SNAKE_CASE : Tuple = model_class(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : Any = model(**self._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase ) ) SCREAMING_SNAKE_CASE : Any = outputs.hidden_states SCREAMING_SNAKE_CASE : int = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(__lowerCAmelCase ) , __lowerCAmelCase ) SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : List[Any] = True check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : Dict = True check_hidden_states_output(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def UpperCAmelCase ( ): SCREAMING_SNAKE_CASE : Optional[int] = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename='''eating_spaghetti.npy''' , repo_type='''dataset''' ) SCREAMING_SNAKE_CASE : Any = np.load(UpperCAmelCase__ ) return list(UpperCAmelCase__ ) @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): @cached_property def __lowercase ( self : List[str] ): """simple docstring""" return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def __lowercase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE : int = TimesformerForVideoClassification.from_pretrained('''facebook/timesformer-base-finetuned-k400''' ).to( __lowerCAmelCase ) SCREAMING_SNAKE_CASE : Dict = self.default_image_processor SCREAMING_SNAKE_CASE : Tuple = prepare_video() SCREAMING_SNAKE_CASE : Tuple = image_processor(video[:8] , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**__lowerCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE : List[Any] = torch.Size((1, 4_00) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) SCREAMING_SNAKE_CASE : int = torch.tensor([-0.3016, -0.7713, -0.4205] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1e-4 ) )
710
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class lowerCamelCase_ ( unittest.TestCase ): def __lowercase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : int = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''的''', '''价''', '''格''', '''是''', '''15''', '''便''', '''alex''', '''##andra''', ''',''', '''。''', '''-''', '''t''', '''shirt''', ] SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE : Optional[Any] = { '''do_resize''': True, '''size''': {'''height''': 2_24, '''width''': 2_24}, '''do_center_crop''': True, '''crop_size''': {'''height''': 18, '''width''': 18}, '''do_normalize''': True, '''image_mean''': [0.4814_5466, 0.457_8275, 0.4082_1073], '''image_std''': [0.2686_2954, 0.2613_0258, 0.2757_7711], '''do_convert_rgb''': True, } SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def __lowercase ( self : str , **lowerCAmelCase__ : int ): """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def __lowercase ( self : Any , **lowerCAmelCase__ : Dict ): """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def __lowercase ( self : List[Any] , **lowerCAmelCase__ : Dict ): """simple docstring""" return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def __lowercase ( self : List[Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowercase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : Optional[Any] = [Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowercase ( self : int ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : Dict = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : List[str] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : int = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Union[str, Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase__ ) def __lowercase ( self : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer(cls_token='''(CLS)''' , sep_token='''(SEP)''' ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor(do_normalize=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Union[str, Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='''(CLS)''' , sep_token='''(SEP)''' , do_normalize=lowerCAmelCase__ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCAmelCase__ ) def __lowercase ( self : Optional[Any] ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.get_image_processor() SCREAMING_SNAKE_CASE : str = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : List[Any] = image_processor(lowerCAmelCase__ , return_tensors='''np''' ) SCREAMING_SNAKE_CASE : List[Any] = processor(images=lowerCAmelCase__ , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : int = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE : Union[str, Any] = processor(text=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[str] = tokenizer(lowerCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowercase ( self : Optional[int] ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : str = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE : Tuple = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : List[str] = processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def __lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : List[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Any = processor.batch_decode(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : Tuple = tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) def __lowercase ( self : Dict ): """simple docstring""" SCREAMING_SNAKE_CASE : str = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Dict = ChineseCLIPProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE : int = '''Alexandra,T-shirt的价格是15便士。''' SCREAMING_SNAKE_CASE : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Any = processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
464
0
'''simple docstring''' import math from collections.abc import Iterator from itertools import takewhile def __lowercase ( __SCREAMING_SNAKE_CASE ) -> bool: """simple docstring""" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(__SCREAMING_SNAKE_CASE ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def __lowercase ( ) -> Iterator[int]: """simple docstring""" __a = 2 while True: if is_prime(__SCREAMING_SNAKE_CASE ): yield num num += 1 def __lowercase ( __SCREAMING_SNAKE_CASE = 200_0000 ) -> int: """simple docstring""" return sum(takewhile(lambda __SCREAMING_SNAKE_CASE : x < n , prime_generator() ) ) if __name__ == "__main__": print(f"""{solution() = }""")
582
'''simple docstring''' from __future__ import annotations class lowerCAmelCase_ : """simple docstring""" def __init__( self : int , SCREAMING_SNAKE_CASE__ : int = 0 ): '''simple docstring''' __a = key def __a ( self : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a = key or self.__key or 1 # make sure key is an appropriate size key %= 2_5_5 return [chr(ord(SCREAMING_SNAKE_CASE__ ) ^ key ) for ch in content] def __a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a = key or self.__key or 1 # make sure key is an appropriate size key %= 2_5_5 return [chr(ord(SCREAMING_SNAKE_CASE__ ) ^ key ) for ch in content] def __a ( self : Any , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int = 0 ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a = key or self.__key or 1 # make sure key can be any size while key > 2_5_5: key -= 2_5_5 # This will be returned __a = """""" for ch in content: ans += chr(ord(SCREAMING_SNAKE_CASE__ ) ^ key ) return ans def __a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int = 0 ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a = key or self.__key or 1 # make sure key can be any size while key > 2_5_5: key -= 2_5_5 # This will be returned __a = """""" for ch in content: ans += chr(ord(SCREAMING_SNAKE_CASE__ ) ^ key ) return ans def __a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int = 0 ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) try: with open(SCREAMING_SNAKE_CASE__ ) as fin, open("""encrypt.out""" , """w+""" ) as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) except OSError: return False return True def __a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) try: with open(SCREAMING_SNAKE_CASE__ ) as fin, open("""decrypt.out""" , """w+""" ) as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
582
1
"""simple docstring""" import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline a_ = version.parse(version.parse(torch.__version__).base_version) < version.parse('1.11') def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=False , ): output_path.parent.mkdir(parents=__UpperCamelCase , exist_ok=__UpperCamelCase ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( __UpperCamelCase , __UpperCamelCase , f=output_path.as_posix() , input_names=__UpperCamelCase , output_names=__UpperCamelCase , dynamic_axes=__UpperCamelCase , do_constant_folding=__UpperCamelCase , use_external_data_format=__UpperCamelCase , enable_onnx_checker=__UpperCamelCase , opset_version=__UpperCamelCase , ) else: export( __UpperCamelCase , __UpperCamelCase , f=output_path.as_posix() , input_names=__UpperCamelCase , output_names=__UpperCamelCase , dynamic_axes=__UpperCamelCase , do_constant_folding=__UpperCamelCase , opset_version=__UpperCamelCase , ) @torch.no_grad() def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = False ): __lowercase : str = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): __lowercase : Optional[Any] = '''cuda''' elif fpaa and not torch.cuda.is_available(): raise ValueError('''`float16` model export is only supported on GPUs with CUDA''' ) else: __lowercase : str = '''cpu''' __lowercase : int = StableDiffusionPipeline.from_pretrained(__UpperCamelCase , torch_dtype=__UpperCamelCase ).to(__UpperCamelCase ) __lowercase : Dict = Path(__UpperCamelCase ) # TEXT ENCODER __lowercase : Optional[Any] = pipeline.text_encoder.config.max_position_embeddings __lowercase : Optional[int] = pipeline.text_encoder.config.hidden_size __lowercase : List[str] = pipeline.tokenizer( '''A sample prompt''' , padding='''max_length''' , max_length=pipeline.tokenizer.model_max_length , truncation=__UpperCamelCase , return_tensors='''pt''' , ) onnx_export( pipeline.text_encoder , model_args=(text_input.input_ids.to(device=__UpperCamelCase , dtype=torch.intaa )) , output_path=output_path / '''text_encoder''' / '''model.onnx''' , ordered_input_names=['''input_ids'''] , output_names=['''last_hidden_state''', '''pooler_output'''] , dynamic_axes={ '''input_ids''': {0: '''batch''', 1: '''sequence'''}, } , opset=__UpperCamelCase , ) del pipeline.text_encoder # UNET __lowercase : Optional[Any] = pipeline.unet.config.in_channels __lowercase : Optional[Any] = pipeline.unet.config.sample_size __lowercase : Tuple = output_path / '''unet''' / '''model.onnx''' onnx_export( pipeline.unet , model_args=( torch.randn(2 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ), torch.randn(2 ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ), torch.randn(2 , __UpperCamelCase , __UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ), False, ) , output_path=__UpperCamelCase , ordered_input_names=['''sample''', '''timestep''', '''encoder_hidden_states''', '''return_dict'''] , output_names=['''out_sample'''] , dynamic_axes={ '''sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, '''timestep''': {0: '''batch'''}, '''encoder_hidden_states''': {0: '''batch''', 1: '''sequence'''}, } , opset=__UpperCamelCase , use_external_data_format=__UpperCamelCase , ) __lowercase : int = str(unet_path.absolute().as_posix() ) __lowercase : Any = os.path.dirname(__UpperCamelCase ) __lowercase : str = onnx.load(__UpperCamelCase ) # clean up existing tensor files shutil.rmtree(__UpperCamelCase ) os.mkdir(__UpperCamelCase ) # collate external tensor files into one onnx.save_model( __UpperCamelCase , __UpperCamelCase , save_as_external_data=__UpperCamelCase , all_tensors_to_one_file=__UpperCamelCase , location='''weights.pb''' , convert_attribute=__UpperCamelCase , ) del pipeline.unet # VAE ENCODER __lowercase : Tuple = pipeline.vae __lowercase : Any = vae_encoder.config.in_channels __lowercase : str = vae_encoder.config.sample_size # need to get the raw tensor output (sample) from the encoder __lowercase : Any = lambda __UpperCamelCase , __UpperCamelCase : vae_encoder.encode(__UpperCamelCase , __UpperCamelCase )[0].sample() onnx_export( __UpperCamelCase , model_args=( torch.randn(1 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ), False, ) , output_path=output_path / '''vae_encoder''' / '''model.onnx''' , ordered_input_names=['''sample''', '''return_dict'''] , output_names=['''latent_sample'''] , dynamic_axes={ '''sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, } , opset=__UpperCamelCase , ) # VAE DECODER __lowercase : Union[str, Any] = pipeline.vae __lowercase : List[str] = vae_decoder.config.latent_channels __lowercase : int = vae_decoder.config.out_channels # forward only through the decoder part __lowercase : str = vae_encoder.decode onnx_export( __UpperCamelCase , model_args=( torch.randn(1 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ), False, ) , output_path=output_path / '''vae_decoder''' / '''model.onnx''' , ordered_input_names=['''latent_sample''', '''return_dict'''] , output_names=['''sample'''] , dynamic_axes={ '''latent_sample''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, } , opset=__UpperCamelCase , ) del pipeline.vae # SAFETY CHECKER if pipeline.safety_checker is not None: __lowercase : Tuple = pipeline.safety_checker __lowercase : List[str] = safety_checker.config.vision_config.num_channels __lowercase : List[Any] = safety_checker.config.vision_config.image_size __lowercase : List[str] = safety_checker.forward_onnx onnx_export( pipeline.safety_checker , model_args=( torch.randn( 1 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ), torch.randn(1 , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ).to(device=__UpperCamelCase , dtype=__UpperCamelCase ), ) , output_path=output_path / '''safety_checker''' / '''model.onnx''' , ordered_input_names=['''clip_input''', '''images'''] , output_names=['''out_images''', '''has_nsfw_concepts'''] , dynamic_axes={ '''clip_input''': {0: '''batch''', 1: '''channels''', 2: '''height''', 3: '''width'''}, '''images''': {0: '''batch''', 1: '''height''', 2: '''width''', 3: '''channels'''}, } , opset=__UpperCamelCase , ) del pipeline.safety_checker __lowercase : Optional[Any] = OnnxRuntimeModel.from_pretrained(output_path / '''safety_checker''' ) __lowercase : List[str] = pipeline.feature_extractor else: __lowercase : Dict = None __lowercase : Tuple = None __lowercase : Union[str, Any] = OnnxStableDiffusionPipeline( vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / '''vae_encoder''' ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / '''vae_decoder''' ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / '''text_encoder''' ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / '''unet''' ) , scheduler=pipeline.scheduler , safety_checker=__UpperCamelCase , feature_extractor=__UpperCamelCase , requires_safety_checker=safety_checker is not None , ) onnx_pipeline.save_pretrained(__UpperCamelCase ) print('''ONNX pipeline saved to''' , __UpperCamelCase ) del pipeline del onnx_pipeline __lowercase : List[Any] = OnnxStableDiffusionPipeline.from_pretrained(__UpperCamelCase , provider='''CPUExecutionProvider''' ) print('''ONNX pipeline is loadable''' ) if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '--model_path', type=str, required=True, help='Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).', ) parser.add_argument('--output_path', type=str, required=True, help='Path to the output model.') parser.add_argument( '--opset', default=1_4, type=int, help='The version of the ONNX operator set to use.', ) parser.add_argument('--fp16', action='store_true', default=False, help='Export the models in `float16` mode') a_ = parser.parse_args() convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
523
"""simple docstring""" from sympy import diff, lambdify, symbols from sympy.functions import * # noqa: F403 def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = "x" , __UpperCamelCase = 10**-10 , __UpperCamelCase = 1 , ): __lowercase : Optional[int] = symbols(__UpperCamelCase ) __lowercase : Tuple = lambdify(__UpperCamelCase , __UpperCamelCase ) __lowercase : Optional[Any] = lambdify(__UpperCamelCase , diff(__UpperCamelCase , __UpperCamelCase ) ) __lowercase : int = starting_point while True: if diff_function(__UpperCamelCase ) != 0: __lowercase : int = prev_guess - multiplicity * func(__UpperCamelCase ) / diff_function( __UpperCamelCase ) else: raise ZeroDivisionError('''Could not find root''' ) from None # Precision is checked by comparing the difference of consecutive guesses if abs(next_guess - prev_guess ) < precision: return next_guess __lowercase : List[str] = next_guess # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") # Find root of polynomial # Find fourth Root of 5 print(F"The root of x**4 - 5 = 0 is {newton_raphson('x**4 -5', 0.4 +5j)}") # Find value of e print( 'The root of log(y) - 1 = 0 is ', F"{newton_raphson('log(y) - 1', 2, variable='y')}", ) # Exponential Roots print( 'The root of exp(x) - 1 = 0 is', F"{newton_raphson('exp(x) - 1', 1_0, precision=0.005)}", ) # Find root of cos(x) print(F"The root of cos(x) = 0 is {newton_raphson('cos(x)', 0)}")
523
1
"""simple docstring""" import requests SCREAMING_SNAKE_CASE__:int = """""" # <-- Put your OpenWeatherMap appid here! SCREAMING_SNAKE_CASE__:Any = """https://api.openweathermap.org/data/2.5/""" def _lowerCamelCase( a = "Chicago" , a = APPID ): return requests.get(URL_BASE + "weather" , params=locals() ).json() def _lowerCamelCase( a = "Kolkata, India" , a = APPID ): return requests.get(URL_BASE + "forecast" , params=locals() ).json() def _lowerCamelCase( a = 55.68 , a = 12.57 , a = APPID ): return requests.get(URL_BASE + "onecall" , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: SCREAMING_SNAKE_CASE__:Tuple = input("""Enter a location:""").strip() if location: pprint(current_weather(location)) else: break
528
"""simple docstring""" import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer SCREAMING_SNAKE_CASE__:List[str] = logging.getLogger(__name__) def _lowerCamelCase( ): __a = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name" , type=a , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , ) parser.add_argument( "--dataset_config" , type=a , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path" , type=a , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , ) parser.add_argument( "--shard_size" , type=a , default=1_0_0_0 , help="Number of entries to go in a single shard." , ) parser.add_argument("--split" , type=a , default="train" , choices=["train", "test", "validation"] ) parser.add_argument( "--limit" , default=a , type=a , help="Limit the number of shards (used for debugging)." , ) parser.add_argument( "--max_length" , type=a , default=5_1_2 , help="Maximum sequence length. For training on TPUs, it helps to have a maximum" " sequence length that is a multiple of 8." , ) parser.add_argument( "--output_dir" , default="tf-tpu" , type=a , help="Output directory where the TFRecord shards will be saved. If the" " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord" " shards will be directly saved to a Google Cloud Storage bucket." , ) __a = parser.parse_args() return args def _lowerCamelCase( a ): def fn(a ): return tokenizer(examples["text"] ) return fn def _lowerCamelCase( a ): __a = [] for i in range(len(tokenized_data["input_ids"] ) ): __a = { "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ), "attention_mask": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ), } __a = tf.train.Features(feature=a ) __a = tf.train.Example(features=a ) __a = example.SerializeToString() records.append(a ) return records def _lowerCamelCase( a ): __a = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: __a = min(len(a ) , args.limit ) __a = dataset.select(range(a ) ) print(F"Limiting the dataset to {args.limit} entries." ) __a = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) __a = os.path.join(args.output_dir , args.split ) if not os.path.exists(a ): os.makedirs(a ) else: __a = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. __a = tokenize_function(a ) __a = dataset.map(a , batched=a , num_proc=4 , remove_columns=["text"] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(a ): # Concatenate all texts. __a = {k: sum(examples[k] , [] ) for k in examples.keys()} __a = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 __a = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. __a = { k: [t[i : i + args.max_length] for i in range(0 , a , args.max_length )] for k, t in concatenated_examples.items() } return result __a = dataset_tokenized.map(a , batched=a , batch_size=1_0_0_0 , num_proc=4 ) __a = 0 __a = 0 for shard in range(0 , len(a ) , args.shard_size ): __a = grouped_dataset[shard : shard + args.shard_size] __a = len(dataset_snapshot["input_ids"] ) __a = os.path.join(a , F"dataset-{shard_count}-{records_containing}.tfrecord" ) __a = get_serialized_examples(a ) with tf.io.TFRecordWriter(a ) as out_file: for i in range(len(a ) ): __a = serialized_examples[i] out_file.write(a ) print("Wrote file {} containing {} records".format(a , a ) ) shard_count += 1 total_records += records_containing with open(F"split-{args.split}-records-count.txt" , "w" ) as f: print(F"Total {args.split} records: {total_records}" , file=a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[Any] = parse_args() main(args)
528
1
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class _UpperCamelCase( __lowerCamelCase ): __SCREAMING_SNAKE_CASE : str = (UnCLIPScheduler,) def __lowerCAmelCase ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' __a : Any = { 'num_train_timesteps': 1_0_0_0, 'variance_type': 'fixed_small_log', 'clip_sample': True, 'clip_sample_range': 1.0, 'prediction_type': 'epsilon', } config.update(**SCREAMING_SNAKE_CASE__ ) return config def __lowerCAmelCase ( self : Dict ): '''simple docstring''' for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : str ): '''simple docstring''' for clip_sample in [True, False]: self.check_over_configs(clip_sample=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' for clip_sample_range in [1, 5, 1_0, 2_0]: self.check_over_configs(clip_sample_range=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : Dict ): '''simple docstring''' for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' for time_step in [0, 5_0_0, 9_9_9]: for prev_timestep in [None, 5, 1_0_0, 2_5_0, 5_0_0, 7_5_0]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=SCREAMING_SNAKE_CASE__ , prev_timestep=SCREAMING_SNAKE_CASE__ ) def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : List[Any] = self.scheduler_classes[0] __a : int = self.get_scheduler_config(variance_type='fixed_small_log' ) __a : Dict = scheduler_class(**SCREAMING_SNAKE_CASE__ ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0000e-10 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.0_549_625 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.9_994_987 ) ) < 1e-5 def __lowerCAmelCase ( self : Any ): '''simple docstring''' __a : Tuple = self.scheduler_classes[0] __a : Dict = self.get_scheduler_config(variance_type='learned_range' ) __a : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a : str = 0.5 assert scheduler._get_variance(1 , predicted_variance=SCREAMING_SNAKE_CASE__ ) - -10.1_712_790 < 1e-5 assert scheduler._get_variance(4_8_7 , predicted_variance=SCREAMING_SNAKE_CASE__ ) - -5.7_998_052 < 1e-5 assert scheduler._get_variance(9_9_9 , predicted_variance=SCREAMING_SNAKE_CASE__ ) - -0.0_010_011 < 1e-5 def __lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' __a : List[Any] = self.scheduler_classes[0] __a : Optional[int] = self.get_scheduler_config() __a : Union[str, Any] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = scheduler.timesteps __a : Tuple = self.dummy_model() __a : Optional[Any] = self.dummy_sample_deter __a : Dict = torch.manual_seed(0 ) for i, t in enumerate(SCREAMING_SNAKE_CASE__ ): # 1. predict noise residual __a : List[Any] = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 2. predict previous mean of sample x_t-1 __a : Dict = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ).prev_sample __a : List[str] = pred_prev_sample __a : List[Any] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Union[str, Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 252.2_682_495 ) < 1e-2 assert abs(result_mean.item() - 0.3_284_743 ) < 1e-3 def __lowerCAmelCase ( self : List[Any] ): '''simple docstring''' __a : Dict = self.scheduler_classes[0] __a : Tuple = self.get_scheduler_config() __a : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(2_5 ) __a : List[Any] = scheduler.timesteps __a : List[Any] = self.dummy_model() __a : Optional[Any] = self.dummy_sample_deter __a : Dict = torch.manual_seed(0 ) for i, t in enumerate(SCREAMING_SNAKE_CASE__ ): # 1. predict noise residual __a : int = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if i + 1 == timesteps.shape[0]: __a : Tuple = None else: __a : List[str] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __a : List[str] = scheduler.step( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , prev_timestep=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ).prev_sample __a : Tuple = pred_prev_sample __a : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) __a : Tuple = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 258.2_044_983 ) < 1e-2 assert abs(result_mean.item() - 0.3_362_038 ) < 1e-3 def __lowerCAmelCase ( self : Dict ): '''simple docstring''' pass def __lowerCAmelCase ( self : List[str] ): '''simple docstring''' pass
706
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated SCREAMING_SNAKE_CASE__ = collections.namedtuple('''_Datasets''', ['''train''', '''validation''', '''test''']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ SCREAMING_SNAKE_CASE__ = '''https://storage.googleapis.com/cvdf-datasets/mnist/''' def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] ): __a : Optional[int] = numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=lowerCamelCase_ )[0] @deprecated(lowerCamelCase_ , 'Please use tf.data to implement this functionality.' ) def UpperCAmelCase__ ( lowerCamelCase_ : Dict ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=lowerCamelCase_ ) as bytestream: __a : Union[str, Any] = _readaa(lowerCamelCase_ ) if magic != 2_0_5_1: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __a : Any = _readaa(lowerCamelCase_ ) __a : int = _readaa(lowerCamelCase_ ) __a : List[Any] = _readaa(lowerCamelCase_ ) __a : str = bytestream.read(rows * cols * num_images ) __a : List[str] = numpy.frombuffer(lowerCamelCase_ , dtype=numpy.uinta ) __a : Optional[Any] = data.reshape(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , 1 ) return data @deprecated(lowerCamelCase_ , 'Please use tf.one_hot on tensors.' ) def UpperCAmelCase__ ( lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[Any] ): __a : List[Any] = labels_dense.shape[0] __a : str = numpy.arange(lowerCamelCase_ ) * num_classes __a : Any = numpy.zeros((num_labels, num_classes) ) __a : List[str] = 1 return labels_one_hot @deprecated(lowerCamelCase_ , 'Please use tf.data to implement this functionality.' ) def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Optional[int]=False , lowerCamelCase_ : int=1_0 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=lowerCamelCase_ ) as bytestream: __a : List[str] = _readaa(lowerCamelCase_ ) if magic != 2_0_4_9: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __a : Optional[int] = _readaa(lowerCamelCase_ ) __a : Dict = bytestream.read(lowerCamelCase_ ) __a : Union[str, Any] = numpy.frombuffer(lowerCamelCase_ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(lowerCamelCase_ , lowerCamelCase_ ) return labels class _UpperCamelCase: @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Any=dtypes.floataa , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : int=None , ): '''simple docstring''' __a , __a : List[Any] = random_seed.get_seed(SCREAMING_SNAKE_CASE__ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __a : Optional[Any] = dtypes.as_dtype(SCREAMING_SNAKE_CASE__ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __a : Dict = 1_0_0_0_0 __a : Tuple = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'''images.shape: {images.shape} labels.shape: {labels.shape}''' __a : List[str] = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __a : Optional[int] = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __a : str = images.astype(numpy.floataa ) __a : Optional[Any] = numpy.multiply(SCREAMING_SNAKE_CASE__ , 1.0 / 255.0 ) __a : int = images __a : Optional[Any] = labels __a : Tuple = 0 __a : Tuple = 0 @property def __lowerCAmelCase ( self : Any ): '''simple docstring''' return self._images @property def __lowerCAmelCase ( self : Dict ): '''simple docstring''' return self._labels @property def __lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' return self._num_examples @property def __lowerCAmelCase ( self : Dict ): '''simple docstring''' return self._epochs_completed def __lowerCAmelCase ( self : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : str=True ): '''simple docstring''' if fake_data: __a : List[Any] = [1] * 7_8_4 __a : Optional[int] = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(SCREAMING_SNAKE_CASE__ )], [fake_label for _ in range(SCREAMING_SNAKE_CASE__ )], ) __a : Optional[Any] = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __a : Union[str, Any] = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = self.images[perma] __a : List[Any] = self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __a : List[str] = self._num_examples - start __a : Tuple = self._images[start : self._num_examples] __a : Union[str, Any] = self._labels[start : self._num_examples] # Shuffle the data if shuffle: __a : str = numpy.arange(self._num_examples ) numpy.random.shuffle(SCREAMING_SNAKE_CASE__ ) __a : Optional[int] = self.images[perm] __a : Any = self.labels[perm] # Start next epoch __a : Dict = 0 __a : List[Any] = batch_size - rest_num_examples __a : str = self._index_in_epoch __a : List[Any] = self._images[start:end] __a : List[Any] = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __a : List[Any] = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(lowerCamelCase_ , 'Please write your own downloading logic.' ) def UpperCAmelCase__ ( lowerCamelCase_ : List[Any] , lowerCamelCase_ : str , lowerCamelCase_ : List[Any] ): if not gfile.Exists(lowerCamelCase_ ): gfile.MakeDirs(lowerCamelCase_ ) __a : Optional[int] = os.path.join(lowerCamelCase_ , lowerCamelCase_ ) if not gfile.Exists(lowerCamelCase_ ): urllib.request.urlretrieve(lowerCamelCase_ , lowerCamelCase_ ) # noqa: S310 with gfile.GFile(lowerCamelCase_ ) as f: __a : str = f.size() print('Successfully downloaded' , lowerCamelCase_ , lowerCamelCase_ , 'bytes.' ) return filepath @deprecated( lowerCamelCase_ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def UpperCAmelCase__ ( lowerCamelCase_ : Optional[Any] , lowerCamelCase_ : Tuple=False , lowerCamelCase_ : Optional[Any]=False , lowerCamelCase_ : Any=dtypes.floataa , lowerCamelCase_ : Optional[int]=True , lowerCamelCase_ : Union[str, Any]=5_0_0_0 , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=lowerCamelCase_ , one_hot=lowerCamelCase_ , dtype=lowerCamelCase_ , seed=lowerCamelCase_ ) __a : List[str] = fake() __a : Union[str, Any] = fake() __a : Optional[Any] = fake() return _Datasets(train=lowerCamelCase_ , validation=lowerCamelCase_ , test=lowerCamelCase_ ) if not source_url: # empty string check __a : Dict = DEFAULT_SOURCE_URL __a : int = 'train-images-idx3-ubyte.gz' __a : List[Any] = 'train-labels-idx1-ubyte.gz' __a : Any = 't10k-images-idx3-ubyte.gz' __a : Optional[int] = 't10k-labels-idx1-ubyte.gz' __a : Optional[int] = _maybe_download( lowerCamelCase_ , lowerCamelCase_ , source_url + train_images_file ) with gfile.Open(lowerCamelCase_ , 'rb' ) as f: __a : List[Any] = _extract_images(lowerCamelCase_ ) __a : Any = _maybe_download( lowerCamelCase_ , lowerCamelCase_ , source_url + train_labels_file ) with gfile.Open(lowerCamelCase_ , 'rb' ) as f: __a : str = _extract_labels(lowerCamelCase_ , one_hot=lowerCamelCase_ ) __a : List[str] = _maybe_download( lowerCamelCase_ , lowerCamelCase_ , source_url + test_images_file ) with gfile.Open(lowerCamelCase_ , 'rb' ) as f: __a : Union[str, Any] = _extract_images(lowerCamelCase_ ) __a : Dict = _maybe_download( lowerCamelCase_ , lowerCamelCase_ , source_url + test_labels_file ) with gfile.Open(lowerCamelCase_ , 'rb' ) as f: __a : Optional[Any] = _extract_labels(lowerCamelCase_ , one_hot=lowerCamelCase_ ) if not 0 <= validation_size <= len(lowerCamelCase_ ): __a : Optional[Any] = ( 'Validation size should be between 0 and ' f'''{len(lowerCamelCase_ )}. Received: {validation_size}.''' ) raise ValueError(lowerCamelCase_ ) __a : int = train_images[:validation_size] __a : Any = train_labels[:validation_size] __a : Optional[Any] = train_images[validation_size:] __a : int = train_labels[validation_size:] __a : Any = {'dtype': dtype, 'reshape': reshape, 'seed': seed} __a : str = _DataSet(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) __a : Any = _DataSet(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) __a : str = _DataSet(lowerCamelCase_ , lowerCamelCase_ , **lowerCamelCase_ ) return _Datasets(train=lowerCamelCase_ , validation=lowerCamelCase_ , test=lowerCamelCase_ )
577
0
"""simple docstring""" from __future__ import annotations import math class UpperCAmelCase : """simple docstring""" def __init__( self , _UpperCAmelCase ): lowercase__: Union[str, Any] = size # approximate the overall size of segment tree with given value lowercase__: Any = [0 for i in range(0 , 4 * size )] # create array to store lazy update lowercase__: Union[str, Any] = [0 for i in range(0 , 4 * size )] lowercase__: Optional[Any] = [0 for i in range(0 , 4 * size )] # flag for lazy update def _snake_case ( self , _UpperCAmelCase ): return idx * 2 def _snake_case ( self , _UpperCAmelCase ): return idx * 2 + 1 def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if left_element == right_element: lowercase__: Optional[int] = a[left_element - 1] else: lowercase__: Any = (left_element + right_element) // 2 self.build(self.left(A__ ) , A__ , A__ , A__ ) self.build(self.right(A__ ) , mid + 1 , A__ , A__ ) lowercase__: List[Any] = max( self.segment_tree[self.left(A__ )] , self.segment_tree[self.right(A__ )] ) def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if self.flag[idx] is True: lowercase__: Dict = self.lazy[idx] lowercase__: str = False if left_element != right_element: lowercase__: Any = self.lazy[idx] lowercase__: Dict = self.lazy[idx] lowercase__: Dict = True lowercase__: int = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: lowercase__: Optional[int] = val if left_element != right_element: lowercase__: Optional[int] = val lowercase__: List[str] = val lowercase__: Dict = True lowercase__: Union[str, Any] = True return True lowercase__: List[Any] = (left_element + right_element) // 2 self.update(self.left(A__ ) , A__ , A__ , A__ , A__ , A__ ) self.update(self.right(A__ ) , mid + 1 , A__ , A__ , A__ , A__ ) lowercase__: Union[str, Any] = max( self.segment_tree[self.left(A__ )] , self.segment_tree[self.right(A__ )] ) return True def _snake_case ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ): if self.flag[idx] is True: lowercase__: Optional[Any] = self.lazy[idx] lowercase__: Tuple = False if left_element != right_element: lowercase__: Any = self.lazy[idx] lowercase__: Union[str, Any] = self.lazy[idx] lowercase__: Dict = True lowercase__: Dict = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] lowercase__: Optional[int] = (left_element + right_element) // 2 lowercase__: Optional[Any] = self.query(self.left(A__ ) , A__ , A__ , A__ , A__ ) lowercase__: Optional[int] = self.query(self.right(A__ ) , mid + 1 , A__ , A__ , A__ ) return max(A__ , A__ ) def __str__( self ): return str([self.query(1 , 1 , self.size , A__ , A__ ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": __A = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] __A = 1_5 __A = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
586
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging A_ : Any = logging.get_logger(__name__) class _a : '''simple docstring''' UpperCAmelCase__: str = None @experimental def UpperCamelCase (lowercase_: int , lowercase_: Any , lowercase_: str , lowercase_: str , lowercase_: List[str] , lowercase_: List[Any] , lowercase_: Union[str, Any] ) -> Union[str, Any]: if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) return _map_with_joblib(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) def UpperCamelCase (lowercase_: Tuple , lowercase_: List[Any] , lowercase_: Tuple , lowercase_: Tuple , lowercase_: List[str] , lowercase_: Dict , lowercase_: Tuple ) -> Tuple: A__ : Union[str, Any] = num_proc if num_proc <= len(lowercase_ ) else len(lowercase_ ) A__ : str = [] # We organize the splits ourselve (contiguous splits) for index in range(lowercase_ ): A__ : Tuple = len(lowercase_ ) // num_proc A__ : Tuple = len(lowercase_ ) % num_proc A__ : Optional[Any] = div * index + min(lowercase_ , lowercase_ ) A__ : Union[str, Any] = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(lowercase_ ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( f"""Error dividing inputs iterable among processes. """ f"""Total number of objects {len(lowercase_ )}, """ f"""length: {sum(len(i[1] ) for i in split_kwds )}""" ) logger.info( f"""Spawning {num_proc} processes for {len(lowercase_ )} objects in slices of {[len(i[1] ) for i in split_kwds]}""" ) A__ , A__ : Optional[int] = None, None if not disable_tqdm: A__ , A__ : List[str] = (RLock(),), tqdm.set_lock with Pool(lowercase_ , initargs=lowercase_ , initializer=lowercase_ ) as pool: A__ : Optional[Any] = pool.map(lowercase_ , lowercase_ ) logger.info(f"""Finished {num_proc} processes""" ) A__ : Tuple = [obj for proc_res in mapped for obj in proc_res] logger.info(f"""Unpacked {len(lowercase_ )} objects""" ) return mapped def UpperCamelCase (lowercase_: Union[str, Any] , lowercase_: Dict , lowercase_: str , lowercase_: Union[str, Any] , lowercase_: List[Any] , lowercase_: Dict , lowercase_: Optional[Any] ) -> Union[str, Any]: # progress bar is not yet supported for _map_with_joblib, because tqdm couldn't accurately be applied to joblib, # and it requires monkey-patching joblib internal classes which is subject to change import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name , n_jobs=lowercase_ ): return joblib.Parallel()( joblib.delayed(lowercase_ )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def UpperCamelCase (lowercase_: str ) -> str: A__ : int = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: A__ : Optional[Any] = None
456
0
from __future__ import annotations def lowerCamelCase_ ( _a : list[list[int]] ): '''simple docstring''' UpperCAmelCase_ : List[Any] = len(_a ) # We need to create solution object to save path. UpperCAmelCase_ : List[Any] = [[0 for _ in range(_a )] for _ in range(_a )] UpperCAmelCase_ : List[Any] = run_maze(_a , 0 , 0 , _a ) if solved: print("""\n""".join(str(_a ) for row in solutions ) ) else: print("""No solution exists!""" ) return solved def lowerCamelCase_ ( _a : list[list[int]] , _a : int , _a : int , _a : list[list[int]] ): '''simple docstring''' UpperCAmelCase_ : str = len(_a ) # Final check point. if i == j == (size - 1): UpperCAmelCase_ : Tuple = 1 return True UpperCAmelCase_ : List[str] = (not i < 0) and (not j < 0) # Check lower bounds UpperCAmelCase_ : List[Any] = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. UpperCAmelCase_ : str = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited UpperCAmelCase_ : List[str] = 1 # check for directions if ( run_maze(_a , i + 1 , _a , _a ) or run_maze(_a , _a , j + 1 , _a ) or run_maze(_a , i - 1 , _a , _a ) or run_maze(_a , _a , j - 1 , _a ) ): return True UpperCAmelCase_ : Optional[Any] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
701
from __future__ import annotations from typing import Any class _snake_case : '''simple docstring''' def __init__( self: Optional[int] ,lowerCamelCase_: int = 6 ) -> None: UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None self.create_linked_list(lowerCamelCase_ ) def A__ ( self: Optional[int] ,lowerCamelCase_: int ) -> None: UpperCAmelCase_ : List[Any] = Node() UpperCAmelCase_ : List[str] = current_node UpperCAmelCase_ : List[Any] = current_node UpperCAmelCase_ : Any = current_node for _ in range(1 ,lowerCamelCase_ ): UpperCAmelCase_ : Optional[int] = Node() UpperCAmelCase_ : Optional[Any] = current_node UpperCAmelCase_ : List[str] = previous_node UpperCAmelCase_ : str = current_node UpperCAmelCase_ : Dict = self.front UpperCAmelCase_ : List[Any] = previous_node def A__ ( self: Any ) -> bool: return ( self.front == self.rear and self.front is not None and self.front.data is None ) def A__ ( self: List[str] ) -> Any | None: self.check_can_perform_operation() return self.front.data if self.front else None def A__ ( self: Tuple ,lowerCamelCase_: Any ) -> None: if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCAmelCase_ : str = self.rear.next if self.rear: UpperCAmelCase_ : int = data def A__ ( self: Optional[int] ) -> Any: self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: UpperCAmelCase_ : Union[str, Any] = self.front.data UpperCAmelCase_ : Dict = None return data UpperCAmelCase_ : Union[str, Any] = self.front UpperCAmelCase_ : Optional[int] = old_front.next UpperCAmelCase_ : Union[str, Any] = old_front.data UpperCAmelCase_ : Optional[Any] = None return data def A__ ( self: str ) -> None: if self.is_empty(): raise Exception("""Empty Queue""" ) def A__ ( self: int ) -> None: if self.rear and self.rear.next == self.front: raise Exception("""Full Queue""" ) class _snake_case : '''simple docstring''' def __init__( self: Tuple ) -> None: UpperCAmelCase_ : Any | None = None UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
322
0
'''simple docstring''' import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class __lowerCAmelCase (lowercase_ , lowercase_ , lowercase_ ): '''simple docstring''' @register_to_config def __init__(self : List[str] , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : float , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : str , UpperCamelCase : bool = False , ): '''simple docstring''' super().__init__() lowercase__ = nn.Embedding(UpperCamelCase , UpperCamelCase ) lowercase__ = nn.Embedding(UpperCamelCase , UpperCamelCase ) lowercase__ = False lowercase__ = nn.Dropout(p=UpperCamelCase ) lowercase__ = TaConfig( vocab_size=UpperCamelCase , d_model=UpperCamelCase , num_heads=UpperCamelCase , d_kv=UpperCamelCase , d_ff=UpperCamelCase , dropout_rate=UpperCamelCase , feed_forward_proj=UpperCamelCase , is_decoder=UpperCamelCase , is_encoder_decoder=UpperCamelCase , ) lowercase__ = nn.ModuleList() for lyr_num in range(UpperCamelCase ): lowercase__ = TaBlock(UpperCamelCase ) self.encoders.append(UpperCamelCase ) lowercase__ = TaLayerNorm(UpperCamelCase ) lowercase__ = nn.Dropout(p=UpperCamelCase ) def UpperCamelCase__ (self : Dict , UpperCamelCase : List[Any] , UpperCamelCase : Dict ): '''simple docstring''' lowercase__ = self.token_embedder(UpperCamelCase ) lowercase__ = encoder_input_tokens.shape[1] lowercase__ = torch.arange(UpperCamelCase , device=encoder_input_tokens.device ) x += self.position_encoding(UpperCamelCase ) lowercase__ = self.dropout_pre(UpperCamelCase ) # inverted the attention mask lowercase__ = encoder_input_tokens.size() lowercase__ = self.get_extended_attention_mask(UpperCamelCase , UpperCamelCase ) for lyr in self.encoders: lowercase__ = lyr(UpperCamelCase , UpperCamelCase )[0] lowercase__ = self.layer_norm(UpperCamelCase ) return self.dropout_post(UpperCamelCase ), encoder_inputs_mask
460
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A = 1_000 ) -> int: """simple docstring""" return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
460
1
"""simple docstring""" from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE_ : Optional[int] = { '''configuration_informer''': [ '''INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_ : Optional[int] = [ '''INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InformerForPrediction''', '''InformerModel''', '''InformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
714
"""simple docstring""" import numpy as np def UpperCAmelCase__ ( A__ ) -> np.array: """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
274
0
"""simple docstring""" import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version A_ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("""4.31.0""") require_version("""datasets>=1.14.0""", """To fix: pip install -r examples/pytorch/audio-classification/requirements.txt""") def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = 16_000 ): lowerCamelCase_ = int(round(sample_rate * max_length ) ) if len(lowerCAmelCase__ ) <= sample_length: return wav lowerCamelCase_ = randint(0 ,len(lowerCAmelCase__ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class __lowerCamelCase : a__: Optional[str] = field(default=lowerCAmelCase , metadata={'help': 'Name of a dataset from the datasets package'} ) a__: Optional[str] = field( default=lowerCAmelCase , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) a__: Optional[str] = field( default=lowerCAmelCase , metadata={'help': 'A file containing the training audio paths and labels.'} ) a__: Optional[str] = field( default=lowerCAmelCase , metadata={'help': 'A file containing the validation audio paths and labels.'} ) a__: str = field( default='train' , metadata={ 'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\'' } , ) a__: str = field( default='validation' , metadata={ 'help': ( 'The name of the training data set split to use (via the datasets library). Defaults to \'validation\'' ) } , ) a__: str = field( default='audio' , metadata={'help': 'The name of the dataset column containing the audio data. Defaults to \'audio\''} , ) a__: str = field( default='label' , metadata={'help': 'The name of the dataset column containing the labels. Defaults to \'label\''} ) a__: Optional[int] = field( default=lowerCAmelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of training examples to this ' 'value if set.' ) } , ) a__: Optional[int] = field( default=lowerCAmelCase , metadata={ 'help': ( 'For debugging purposes or quicker training, truncate the number of evaluation examples to this ' 'value if set.' ) } , ) a__: float = field( default=20 , metadata={'help': 'Audio clips will be randomly cut to this length during training if the value is set.'} , ) @dataclass class __lowerCamelCase : a__: str = field( default='facebook/wav2vec2-base' , metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} , ) a__: Optional[str] = field( default=lowerCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) a__: Optional[str] = field( default=lowerCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from the Hub'} ) a__: str = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) a__: Optional[str] = field( default=lowerCAmelCase , metadata={'help': 'Name or path of preprocessor config.'} ) a__: bool = field( default=lowerCAmelCase , metadata={'help': 'Whether to freeze the feature encoder layers of the model.'} ) a__: bool = field( default=lowerCAmelCase , metadata={'help': 'Whether to generate an attention mask in the feature extractor.'} ) a__: bool = field( default=lowerCAmelCase , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) a__: Optional[bool] = field( default=lowerCAmelCase , metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} ) a__: bool = field( default=lowerCAmelCase , metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'} , ) def UpperCAmelCase__ ( self ): if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''will be removed in a future version. Use `--freeze_feature_encoder`''' '''instead. Setting `freeze_feature_encoder==True`.''' , UpperCAmelCase , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( '''The argument `--freeze_feature_extractor` is deprecated and ''' '''should not be used in combination with `--freeze_feature_encoder`.''' '''Only make use of `--freeze_feature_encoder`.''' ) def lowercase ( ): # 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. lowerCamelCase_ = 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. lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_audio_classification''' ,lowerCAmelCase__ ,lowerCAmelCase__ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' ,datefmt='''%m/%d/%Y %H:%M:%S''' ,handlers=[logging.StreamHandler(sys.stdout )] ,) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() lowerCamelCase_ = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase__ ) transformers.utils.logging.set_verbosity(lowerCAmelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} " + f"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(f"Training/evaluation parameters {training_args}" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. lowerCamelCase_ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: lowerCamelCase_ = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " '''Use --overwrite_output_dir to train from scratch.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Initialize our dataset and prepare it for the audio classification task. lowerCamelCase_ = DatasetDict() lowerCamelCase_ = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.train_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) lowerCamelCase_ = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=data_args.eval_split_name ,use_auth_token=True if model_args.use_auth_token else None ,) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. " '''Make sure to set `--audio_column_name` to the correct audio column - one of ''' f"{', '.join(raw_datasets['train'].column_names )}." ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( f"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. " '''Make sure to set `--label_column_name` to the correct text column - one of ''' f"{', '.join(raw_datasets['train'].column_names )}." ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy lowerCamelCase_ = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path ,return_attention_mask=model_args.attention_mask ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. lowerCamelCase_ = raw_datasets.cast_column( data_args.audio_column_name ,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) lowerCamelCase_ = feature_extractor.model_input_names[0] def train_transforms(lowerCAmelCase__ ): lowerCamelCase_ = [] for audio in batch[data_args.audio_column_name]: lowerCamelCase_ = random_subsample( audio['''array'''] ,max_length=data_args.max_length_seconds ,sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(lowerCAmelCase__ ) lowerCamelCase_ = feature_extractor(lowerCAmelCase__ ,sampling_rate=feature_extractor.sampling_rate ) lowerCamelCase_ = {model_input_name: inputs.get(lowerCAmelCase__ )} lowerCamelCase_ = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(lowerCAmelCase__ ): lowerCamelCase_ = [audio['''array'''] for audio in batch[data_args.audio_column_name]] lowerCamelCase_ = feature_extractor(lowerCAmelCase__ ,sampling_rate=feature_extractor.sampling_rate ) lowerCamelCase_ = {model_input_name: inputs.get(lowerCAmelCase__ )} lowerCamelCase_ = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. lowerCamelCase_ = raw_datasets['''train'''].features[data_args.label_column_name].names lowerCamelCase_ , lowerCamelCase_ = {}, {} for i, label in enumerate(lowerCAmelCase__ ): lowerCamelCase_ = str(lowerCAmelCase__ ) lowerCamelCase_ = label # Load the accuracy metric from the datasets package lowerCamelCase_ = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(lowerCAmelCase__ ): lowerCamelCase_ = np.argmax(eval_pred.predictions ,axis=1 ) return metric.compute(predictions=lowerCAmelCase__ ,references=eval_pred.label_ids ) lowerCamelCase_ = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path ,num_labels=len(lowerCAmelCase__ ) ,labelaid=lowerCAmelCase__ ,idalabel=lowerCAmelCase__ ,finetuning_task='''audio-classification''' ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) lowerCamelCase_ = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) ,config=lowerCAmelCase__ ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes ,) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: lowerCamelCase_ = ( raw_datasets['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(lowerCAmelCase__ ,output_all_columns=lowerCAmelCase__ ) if training_args.do_eval: if data_args.max_eval_samples is not None: lowerCamelCase_ = ( raw_datasets['''eval'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(lowerCAmelCase__ ,output_all_columns=lowerCAmelCase__ ) # Initialize our trainer lowerCamelCase_ = Trainer( model=lowerCAmelCase__ ,args=lowerCAmelCase__ ,train_dataset=raw_datasets['''train'''] if training_args.do_train else None ,eval_dataset=raw_datasets['''eval'''] if training_args.do_eval else None ,compute_metrics=lowerCAmelCase__ ,tokenizer=lowerCAmelCase__ ,) # Training if training_args.do_train: lowerCamelCase_ = None if training_args.resume_from_checkpoint is not None: lowerCamelCase_ = training_args.resume_from_checkpoint elif last_checkpoint is not None: lowerCamelCase_ = last_checkpoint lowerCamelCase_ = trainer.train(resume_from_checkpoint=lowerCAmelCase__ ) trainer.save_model() trainer.log_metrics('''train''' ,train_result.metrics ) trainer.save_metrics('''train''' ,train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: lowerCamelCase_ = trainer.evaluate() trainer.log_metrics('''eval''' ,lowerCAmelCase__ ) trainer.save_metrics('''eval''' ,lowerCAmelCase__ ) # Write model card and (optionally) push to hub lowerCamelCase_ = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''audio-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''audio-classification'''], } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase__ ) else: trainer.create_model_card(**lowerCAmelCase__ ) if __name__ == "__main__": main()
29
'''simple docstring''' import socket def lowerCAmelCase__ ( ): _A : Dict = socket.socket(socket.AF_INET ,socket.SOCK_STREAM ) _A : List[Any] = socket.gethostname() _A : List[str] = 12312 sock.connect((host, port) ) sock.send(b'Hello server!' ) with open('Received_file' ,'wb' ) as out_file: print('File opened' ) print('Receiving data...' ) while True: _A : Optional[int] = sock.recv(1024 ) if not data: break out_file.write(lowerCamelCase ) print('Successfully received the file' ) sock.close() print('Connection closed' ) if __name__ == "__main__": main()
128
0
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision 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 MobileViTImageProcessor class _lowercase ( unittest.TestCase ): def __init__( self , A__ , A__=7 , A__=3 , A__=18 , A__=30 , A__=4_00 , A__=True , A__=None , A__=True , A__=None , A__=True , ) -> Dict: snake_case = size if size is not None else {'''shortest_edge''': 20} snake_case = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} snake_case = parent snake_case = batch_size snake_case = num_channels snake_case = image_size snake_case = min_resolution snake_case = max_resolution snake_case = do_resize snake_case = size snake_case = do_center_crop snake_case = crop_size snake_case = do_flip_channel_order def UpperCamelCase ( self ) -> Tuple: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class _lowercase ( __a , unittest.TestCase ): _UpperCAmelCase = MobileViTImageProcessor if is_vision_available() else None def UpperCamelCase ( self ) -> str: snake_case = MobileViTImageProcessingTester(self ) @property def UpperCamelCase ( self ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase ( self ) -> Dict: snake_case = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A__ , '''do_resize''' ) ) self.assertTrue(hasattr(A__ , '''size''' ) ) self.assertTrue(hasattr(A__ , '''do_center_crop''' ) ) self.assertTrue(hasattr(A__ , '''center_crop''' ) ) self.assertTrue(hasattr(A__ , '''do_flip_channel_order''' ) ) def UpperCamelCase ( self ) -> Optional[Any]: snake_case = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) snake_case = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) def UpperCamelCase ( self ) -> Any: pass def UpperCamelCase ( self ) -> Dict: # Initialize image_processing snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ ) for image in image_inputs: self.assertIsInstance(A__ , Image.Image ) # Test not batched input snake_case = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case = image_processing(A__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCamelCase ( self ) -> Dict: # Initialize image_processing snake_case = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , numpify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , np.ndarray ) # Test not batched input snake_case = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case = image_processing(A__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def UpperCamelCase ( self ) -> str: # Initialize image_processing snake_case = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case = prepare_image_inputs(self.image_processor_tester , equal_resolution=A__ , torchify=A__ ) for image in image_inputs: self.assertIsInstance(A__ , torch.Tensor ) # Test not batched input snake_case = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched snake_case = image_processing(A__ , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , )
44
'''simple docstring''' from __future__ import annotations import inspect import unittest from transformers import ViTConfig 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 TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _lowercase : def __init__( self , A__ , A__=13 , A__=30 , A__=2 , A__=3 , A__=True , A__=True , A__=32 , A__=2 , A__=4 , A__=37 , A__="gelu" , A__=0.1 , A__=0.1 , A__=10 , A__=0.0_2 , A__=3 , A__=None , ) -> List[Any]: snake_case = parent snake_case = batch_size snake_case = image_size snake_case = patch_size snake_case = num_channels snake_case = is_training snake_case = use_labels snake_case = hidden_size snake_case = num_hidden_layers snake_case = num_attention_heads snake_case = intermediate_size snake_case = hidden_act snake_case = hidden_dropout_prob snake_case = attention_probs_dropout_prob snake_case = type_sequence_label_size snake_case = initializer_range snake_case = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) snake_case = (image_size // patch_size) ** 2 snake_case = num_patches + 1 def UpperCamelCase ( self ) -> int: snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case = None if self.use_labels: snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case = self.get_config() return config, pixel_values, labels def UpperCamelCase ( self ) -> int: return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=A__ , initializer_range=self.initializer_range , ) def UpperCamelCase ( self , A__ , A__ , A__ ) -> Union[str, Any]: snake_case = TFViTModel(config=A__ ) snake_case = model(A__ , training=A__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. snake_case = self.image_size // 2 snake_case = pixel_values[:, :, :image_size, :image_size] snake_case = model(A__ , interpolate_pos_encoding=A__ , training=A__ ) snake_case = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def UpperCamelCase ( self , A__ , A__ , A__ ) -> Optional[int]: snake_case = self.type_sequence_label_size snake_case = TFViTForImageClassification(A__ ) snake_case = model(A__ , labels=A__ , training=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. snake_case = self.image_size // 2 snake_case = pixel_values[:, :, :image_size, :image_size] snake_case = model(A__ , interpolate_pos_encoding=A__ , training=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images snake_case = 1 snake_case = TFViTForImageClassification(A__ ) snake_case = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case = model(A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase ( self ) -> Union[str, Any]: snake_case = self.prepare_config_and_inputs() snake_case , snake_case , snake_case = config_and_inputs snake_case = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class _lowercase ( __a , __a , unittest.TestCase ): _UpperCAmelCase = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () _UpperCAmelCase = ( {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification} if is_tf_available() else {} ) _UpperCAmelCase = False _UpperCAmelCase = False _UpperCAmelCase = False def UpperCamelCase ( self ) -> List[Any]: snake_case = TFViTModelTester(self ) snake_case = ConfigTester(self , config_class=A__ , has_text_modality=A__ , hidden_size=37 ) def UpperCamelCase ( self ) -> int: self.config_tester.run_common_tests() @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def UpperCamelCase ( self ) -> int: pass @unittest.skip(reason='''ViT does not use inputs_embeds''' ) def UpperCamelCase ( self ) -> str: pass def UpperCamelCase ( self ) -> Union[str, Any]: snake_case , snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case = model_class(A__ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) snake_case = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A__ , tf.keras.layers.Layer ) ) def UpperCamelCase ( self ) -> List[Any]: snake_case , snake_case = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case = model_class(A__ ) snake_case = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case = [*signature.parameters.keys()] snake_case = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , A__ ) def UpperCamelCase ( self ) -> Union[str, Any]: snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A__ ) def UpperCamelCase ( self ) -> Optional[Any]: snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A__ ) @slow def UpperCamelCase ( self ) -> Any: snake_case = TFViTModel.from_pretrained('''google/vit-base-patch16-224''' ) self.assertIsNotNone(A__ ) def __UpperCamelCase ( ) ->Any: snake_case = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class _lowercase ( unittest.TestCase ): @cached_property def UpperCamelCase ( self ) -> Optional[int]: return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''' ) if is_vision_available() else None @slow def UpperCamelCase ( self ) -> Dict: snake_case = TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''' ) snake_case = self.default_image_processor snake_case = prepare_img() snake_case = image_processor(images=A__ , return_tensors='''tf''' ) # forward pass snake_case = model(**A__ ) # verify the logits snake_case = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , A__ ) snake_case = tf.constant([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ) tf.debugging.assert_near(outputs.logits[0, :3] , A__ , atol=1e-4 )
44
1
'''simple docstring''' import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import datasets import datasets.config from .utils import require_beam class __snake_case ( datasets.BeamBasedBuilder ): '''simple docstring''' def __UpperCamelCase ( self ): return datasets.DatasetInfo( features=datasets.Features({"""content""": datasets.Value("""string""" )} ) , supervised_keys=__lowerCamelCase , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_dummy_examples()} )] def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(__lowerCamelCase ) class __snake_case ( datasets.BeamBasedBuilder ): '''simple docstring''' def __UpperCamelCase ( self ): return datasets.DatasetInfo( features=datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) , supervised_keys=__lowerCamelCase , ) def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return [ datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""examples""": get_test_nested_examples()} ) ] def __UpperCamelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): import apache_beam as beam return pipeline | "Load Examples" >> beam.Create(__lowerCamelCase ) def UpperCamelCase__ ( ) -> Any: '''simple docstring''' return [(i, {"content": content}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] def UpperCamelCase__ ( ) -> List[str]: '''simple docstring''' return [(i, {"a": {"b": [content]}}) for i, content in enumerate(["""foo""", """bar""", """foobar"""] )] class __snake_case ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @require_beam def __UpperCamelCase ( self ): snake_case__ : List[str] = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case__ : List[str] = DummyBeamDataset(cache_dir=__lowerCamelCase , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(__lowerCamelCase , builder.name , """default""" , """0.0.0""" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) snake_case__ : List[Any] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , __lowerCamelCase ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , __lowerCamelCase ) self.assertDictEqual(dset["""train"""][0] , get_test_dummy_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_dummy_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(__lowerCamelCase , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __UpperCamelCase ( self ): import apache_beam as beam snake_case__ : str = beam.io.parquetio.WriteToParquet snake_case__ : int = len(get_test_dummy_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case__ : Union[str, Any] = DummyBeamDataset(cache_dir=__lowerCamelCase , beam_runner="""DirectRunner""" ) with patch("""apache_beam.io.parquetio.WriteToParquet""" ) as write_parquet_mock: snake_case__ : Union[str, Any] = partial(__lowerCamelCase , num_shards=2 ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join( __lowerCamelCase , builder.name , """default""" , """0.0.0""" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertTrue( os.path.exists( os.path.join( __lowerCamelCase , builder.name , """default""" , """0.0.0""" , f"{builder.name}-train-00000-of-00002.arrow" ) ) ) self.assertDictEqual(builder.info.features , datasets.Features({"""content""": datasets.Value("""string""" )} ) ) snake_case__ : Any = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , __lowerCamelCase ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , __lowerCamelCase ) # Order is not preserved when sharding, so we just check that all the elements are there self.assertListEqual(sorted(dset["""train"""]["""content"""] ) , sorted(["""foo""", """bar""", """foobar"""] ) ) self.assertTrue( os.path.exists(os.path.join(__lowerCamelCase , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset @require_beam def __UpperCamelCase ( self ): with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case__ : str = DummyBeamDataset(cache_dir=__lowerCamelCase ) self.assertRaises(datasets.builder.MissingBeamOptions , builder.download_and_prepare ) @require_beam def __UpperCamelCase ( self ): snake_case__ : Any = len(get_test_nested_examples() ) with tempfile.TemporaryDirectory() as tmp_cache_dir: snake_case__ : int = NestedBeamDataset(cache_dir=__lowerCamelCase , beam_runner="""DirectRunner""" ) builder.download_and_prepare() self.assertTrue( os.path.exists( os.path.join(__lowerCamelCase , builder.name , """default""" , """0.0.0""" , f"{builder.name}-train.arrow" ) ) ) self.assertDictEqual( builder.info.features , datasets.Features({"""a""": datasets.Sequence({"""b""": datasets.Value("""string""" )} )} ) ) snake_case__ : List[str] = builder.as_dataset() self.assertEqual(dset["""train"""].num_rows , __lowerCamelCase ) self.assertEqual(dset["""train"""].info.splits["""train"""].num_examples , __lowerCamelCase ) self.assertDictEqual(dset["""train"""][0] , get_test_nested_examples()[0][1] ) self.assertDictEqual( dset["""train"""][expected_num_examples - 1] , get_test_nested_examples()[expected_num_examples - 1][1] ) self.assertTrue( os.path.exists(os.path.join(__lowerCamelCase , builder.name , """default""" , """0.0.0""" , """dataset_info.json""" ) ) ) del dset
38
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = '▁' lowerCAmelCase__ = {'vocab_file': 'sentencepiece.bpe.model'} lowerCAmelCase__ = { 'vocab_file': { 'facebook/mbart-large-en-ro': ( 'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model' ), 'facebook/mbart-large-cc25': ( 'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model' ), } } lowerCAmelCase__ = { 'facebook/mbart-large-en-ro': 10_24, 'facebook/mbart-large-cc25': 10_24, } # fmt: off lowerCAmelCase__ = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN'] class lowerCAmelCase__ ( a): '''simple docstring''' __SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES __SCREAMING_SNAKE_CASE = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP __SCREAMING_SNAKE_CASE = ["input_ids", "attention_mask"] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] def __init__( self , __lowerCamelCase , __lowerCamelCase="<s>" , __lowerCamelCase="</s>" , __lowerCamelCase="</s>" , __lowerCamelCase="<s>" , __lowerCamelCase="<unk>" , __lowerCamelCase="<pad>" , __lowerCamelCase="<mask>" , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase = None , __lowerCamelCase=None , **__lowerCamelCase , ) -> int: # Mask token behave like a normal word, i.e. include the space before it _A : Union[str, Any] = AddedToken(__lowerCamelCase , lstrip=__lowerCamelCase , rstrip=__lowerCamelCase) if isinstance(__lowerCamelCase , __lowerCamelCase) else mask_token _A : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowerCamelCase , eos_token=__lowerCamelCase , unk_token=__lowerCamelCase , sep_token=__lowerCamelCase , cls_token=__lowerCamelCase , pad_token=__lowerCamelCase , mask_token=__lowerCamelCase , tokenizer_file=__lowerCamelCase , src_lang=__lowerCamelCase , tgt_lang=__lowerCamelCase , additional_special_tokens=__lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__lowerCamelCase , ) _A : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.Load(str(__lowerCamelCase)) _A : str = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token _A : List[Any] = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab _A : Optional[int] = 1 _A : Dict = len(self.sp_model) _A : List[str] = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__lowerCamelCase) } _A : Optional[int] = {v: k for k, v in self.lang_code_to_id.items()} _A : List[str] = len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id) _A : Tuple = {v: k for k, v in self.fairseq_tokens_to_ids.items()} _A : int = list(self.lang_code_to_id.keys()) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens]) _A : Tuple = src_lang if src_lang is not None else "en_XX" _A : List[Any] = self.lang_code_to_id[self._src_lang] _A : Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self._src_lang) def __getstate__( self) -> List[Any]: _A : Optional[Any] = self.__dict__.copy() _A : List[str] = None _A : List[str] = self.sp_model.serialized_model_proto() return state def __setstate__( self , __lowerCamelCase) -> Dict: _A : int = d # for backward compatibility if not hasattr(self , "sp_model_kwargs"): _A : Optional[Any] = {} _A : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs) self.sp_model.LoadFromSerializedProto(self.sp_model_proto) @property def _lowerCamelCase ( self) -> Tuple: return len(self.sp_model) + len(self.lang_code_to_id) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _lowerCamelCase ( self) -> str: return self._src_lang @src_lang.setter def _lowerCamelCase ( self , __lowerCamelCase) -> None: _A : List[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = False) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowerCamelCase , token_ids_a=__lowerCamelCase , already_has_special_tokens=__lowerCamelCase) _A : Optional[int] = [1] * len(self.prefix_tokens) _A : Tuple = [1] * len(self.suffix_tokens) if token_ids_a is None: return prefix_ones + ([0] * len(__lowerCamelCase)) + suffix_ones return prefix_ones + ([0] * len(__lowerCamelCase)) + ([0] * len(__lowerCamelCase)) + suffix_ones def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase = None) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase = None) -> List[int]: _A : Optional[int] = [self.sep_token_id] _A : Optional[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 _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , **__lowerCamelCase) -> Optional[int]: if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model") _A : int = src_lang _A : Any = self(__lowerCamelCase , add_special_tokens=__lowerCamelCase , return_tensors=__lowerCamelCase , **__lowerCamelCase) _A : Any = self.convert_tokens_to_ids(__lowerCamelCase) _A : int = tgt_lang_id return inputs def _lowerCamelCase ( self) -> Dict: _A : int = {self.convert_ids_to_tokens(__lowerCamelCase): i for i in range(self.vocab_size)} vocab.update(self.added_tokens_encoder) return vocab def _lowerCamelCase ( self , __lowerCamelCase) -> List[str]: return self.sp_model.encode(__lowerCamelCase , out_type=__lowerCamelCase) def _lowerCamelCase ( self , __lowerCamelCase) -> Optional[Any]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] _A : List[str] = self.sp_model.PieceToId(__lowerCamelCase) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _lowerCamelCase ( self , __lowerCamelCase) -> Dict: if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset) def _lowerCamelCase ( self , __lowerCamelCase) -> Optional[Any]: _A : Optional[Any] = "".join(__lowerCamelCase).replace(__lowerCamelCase , " ").strip() return out_string def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase = None) -> Tuple[str]: if not os.path.isdir(__lowerCamelCase): logger.error(F"Vocabulary path ({save_directory}) should be a directory") return _A : Union[str, Any] = os.path.join( __lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]) if os.path.abspath(self.vocab_file) != os.path.abspath(__lowerCamelCase) and os.path.isfile(self.vocab_file): copyfile(self.vocab_file , __lowerCamelCase) elif not os.path.isfile(self.vocab_file): with open(__lowerCamelCase , "wb") as fi: _A : List[Any] = self.sp_model.serialized_model_proto() fi.write(__lowerCamelCase) return (out_vocab_file,) def _lowerCamelCase ( self , __lowerCamelCase , __lowerCamelCase = "en_XX" , __lowerCamelCase = None , __lowerCamelCase = "ro_RO" , **__lowerCamelCase , ) -> BatchEncoding: _A : Optional[int] = src_lang _A : Optional[Any] = tgt_lang return super().prepare_seqaseq_batch(__lowerCamelCase , __lowerCamelCase , **__lowerCamelCase) def _lowerCamelCase ( self) -> int: return self.set_src_lang_special_tokens(self.src_lang) def _lowerCamelCase ( self) -> int: return self.set_tgt_lang_special_tokens(self.tgt_lang) def _lowerCamelCase ( self , __lowerCamelCase) -> None: _A : str = self.lang_code_to_id[src_lang] _A : Any = [] _A : Dict = [self.eos_token_id, self.cur_lang_code] def _lowerCamelCase ( self , __lowerCamelCase) -> None: _A : Any = self.lang_code_to_id[lang] _A : str = [] _A : Union[str, Any] = [self.eos_token_id, self.cur_lang_code]
503
0
import inspect import unittest from transformers import MobileViTVaConfig 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, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel from transformers.models.mobilevitva.modeling_mobilevitva import ( MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST, make_divisible, ) if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class _A( snake_case__ ): """simple docstring""" def UpperCAmelCase_ ( self ): __A : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_A , 'width_multiplier' ) ) class _A: """simple docstring""" def __init__( self , _A , _A=13 , _A=64 , _A=2 , _A=3 , _A="swish" , _A=3 , _A=32 , _A=0.1 , _A=0.0_2 , _A=True , _A=True , _A=10 , _A=None , _A=0.2_5 , _A=0.0 , _A=0.0 , ): __A : Optional[Any] = parent __A : Dict = batch_size __A : Union[str, Any] = image_size __A : Dict = patch_size __A : Tuple = num_channels __A : List[Any] = make_divisible(512 * width_multiplier , divisor=8 ) __A : List[str] = hidden_act __A : Union[str, Any] = conv_kernel_size __A : Union[str, Any] = output_stride __A : Union[str, Any] = classifier_dropout_prob __A : str = use_labels __A : Optional[int] = is_training __A : Any = num_labels __A : Any = initializer_range __A : Tuple = scope __A : Optional[Any] = width_multiplier __A : str = ffn_dropout __A : Dict = attn_dropout def UpperCAmelCase_ ( self ): __A : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A : Union[str, Any] = None __A : List[str] = None if self.use_labels: __A : List[str] = ids_tensor([self.batch_size] , self.num_labels ) __A : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __A : Any = self.get_config() return config, pixel_values, labels, pixel_labels def UpperCAmelCase_ ( self ): return MobileViTVaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , width_multiplier=self.width_multiplier , ffn_dropout=self.ffn_dropout_prob , attn_dropout=self.attn_dropout_prob , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A ): __A : Union[str, Any] = MobileViTVaModel(config=_A ) model.to(_A ) model.eval() __A : Any = model(_A ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCAmelCase_ ( self , _A , _A , _A , _A ): __A : List[Any] = self.num_labels __A : Union[str, Any] = MobileViTVaForImageClassification(_A ) model.to(_A ) model.eval() __A : List[str] = model(_A , labels=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self , _A , _A , _A , _A ): __A : Dict = self.num_labels __A : Dict = MobileViTVaForSemanticSegmentation(_A ) model.to(_A ) model.eval() __A : Tuple = model(_A ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __A : Optional[int] = model(_A , labels=_A ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def UpperCAmelCase_ ( self ): __A : Optional[Any] = self.prepare_config_and_inputs() __A , __A , __A , __A : Optional[int] = config_and_inputs __A : List[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class _A( snake_case__ , snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : int = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase : int = ( { '''feature-extraction''': MobileViTVaModel, '''image-classification''': MobileViTVaForImageClassification, '''image-segmentation''': MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase : int = False UpperCamelCase : Dict = False UpperCamelCase : Tuple = False UpperCamelCase : str = False def UpperCAmelCase_ ( self ): __A : Optional[int] = MobileViTVaModelTester(self ) __A : int = MobileViTVaConfigTester(self , config_class=_A , has_text_modality=_A ) def UpperCAmelCase_ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason='MobileViTV2 does not use inputs_embeds' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='MobileViTV2 does not support input and output embeddings' ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason='MobileViTV2 does not output attentions' ) def UpperCAmelCase_ ( self ): pass @require_torch_multi_gpu @unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.' ) 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 ): __A , __A : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : Optional[int] = model_class(_A ) __A : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A : Tuple = [*signature.parameters.keys()] __A : Tuple = ['pixel_values'] self.assertListEqual(arg_names[:1] , _A ) def UpperCAmelCase_ ( self ): __A : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def UpperCAmelCase_ ( self ): def check_hidden_states_output(_A , _A , _A ): __A : Optional[int] = model_class(_A ) model.to(_A ) model.eval() with torch.no_grad(): __A : Dict = model(**self._prepare_for_class(_A , _A ) ) __A : Optional[int] = outputs.hidden_states __A : Any = 5 self.assertEqual(len(_A ) , _A ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __A : Optional[Any] = 2 for i in range(len(_A ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __A , __A : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A : List[str] = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A : Optional[Any] = True check_hidden_states_output(_A , _A , _A ) def UpperCAmelCase_ ( self ): __A : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) def UpperCAmelCase_ ( self ): __A : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*_A ) @slow def UpperCAmelCase_ ( self ): for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A : List[str] = MobileViTVaModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def _SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: __A : Tuple = 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 ): return ( MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self ): __A : Dict = MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256' ).to( _A ) __A : Tuple = self.default_image_processor __A : Union[str, Any] = prepare_img() __A : int = image_processor(images=_A , return_tensors='pt' ).to(_A ) # forward pass with torch.no_grad(): __A : str = model(**_A ) # verify the logits __A : Dict = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _A ) __A : Dict = torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1] ).to(_A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _A , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): __A : List[str] = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) __A : Union[str, Any] = model.to(_A ) __A : int = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) __A : Union[str, Any] = prepare_img() __A : Dict = image_processor(images=_A , return_tensors='pt' ).to(_A ) # forward pass with torch.no_grad(): __A : int = model(**_A ) __A : Optional[int] = outputs.logits # verify the logits __A : List[str] = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , _A ) __A : Dict = torch.tensor( [ [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]], [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]], [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]], ] , device=_A , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , _A , atol=1e-4 ) ) @slow def UpperCAmelCase_ ( self ): __A : Tuple = MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) __A : str = model.to(_A ) __A : Union[str, Any] = MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3' ) __A : Union[str, Any] = prepare_img() __A : List[Any] = image_processor(images=_A , return_tensors='pt' ).to(_A ) # forward pass with torch.no_grad(): __A : str = model(**_A ) __A : Dict = outputs.logits.detach().cpu() __A : Optional[int] = image_processor.post_process_semantic_segmentation(outputs=_A , target_sizes=[(50, 60)] ) __A : Dict = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , _A ) __A : List[str] = image_processor.post_process_semantic_segmentation(outputs=_A ) __A : str = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , _A )
77
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel UpperCAmelCase : str = HfApi() UpperCAmelCase : List[str] = {} # fmt: off UpperCAmelCase : Optional[Any] = torch.tensor([ -0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467, 1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189, -1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839, 0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557 ]) UpperCAmelCase : Dict = torch.tensor([ -2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436, 1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208, -2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948, 2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869, -0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304, -0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925, 0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943 ]) UpperCAmelCase : str = torch.tensor([ 0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172, -0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309, 0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805, -0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505 ]) UpperCAmelCase : Optional[Any] = torch.tensor([ 0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133, -0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395, 0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559, -0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386 ]) UpperCAmelCase : List[Any] = torch.tensor([ 0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078, -0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330, 0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683, -0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431 ]) UpperCAmelCase : Optional[int] = torch.tensor([ 0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042, -0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398, 0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574, -0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390 ]) UpperCAmelCase : Tuple = torch.tensor([ 0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042, -0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290, 0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746, -0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473 ]) UpperCAmelCase : Any = torch.tensor([ -1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330, 1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243, -2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810, 1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324, 0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181, -2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259, 1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266 ]) UpperCAmelCase : Tuple = torch.tensor([ -1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212, 0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027, -2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131, 1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355 ]) UpperCAmelCase : Dict = torch.tensor([ -2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959, 1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351, -3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341, 3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066 ]) UpperCAmelCase : Tuple = torch.tensor([ -2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740, 1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398, -2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395, 2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243 ]) UpperCAmelCase : List[str] = torch.tensor([ -2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336, 1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908, -3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560, 3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343 ]) UpperCAmelCase : Union[str, Any] = torch.tensor([ -1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344, 1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391, -2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439, 1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219 ]) # fmt: on UpperCAmelCase : Any = api.list_models(filter='''diffusers''') for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1] print(F"""Started running {mod.modelId}!!!""") if mod.modelId.startswith('''CompVis'''): UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''') else: UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): UpperCAmelCase : Any = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3 ) print(F"""{mod.modelId} has passed successfully!!!""")
77
1
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(A ) , '''Tatoeba directory does not exist.''' ) class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def __snake_case( self ): _UpperCAmelCase : Optional[Any] = tempfile.mkdtemp() return TatoebaConverter(save_dir=A_ ) @slow def __snake_case( self ): self.resolver.convert_models(["""heb-eng"""] ) @slow def __snake_case( self ): _UpperCAmelCase,_UpperCAmelCase : Any = self.resolver.write_model_card("""opus-mt-he-en""" , dry_run=A_ ) assert mmeta["long_pair"] == "heb-eng"
643
from __future__ import annotations def a__ ( snake_case__ : list[int] ): if len(snake_case__ ) == 0: return array _UpperCAmelCase,_UpperCAmelCase : List[str] = min(snake_case__ ), max(snake_case__ ) # Compute the variables _UpperCAmelCase : Tuple = _max - _min + 1 _UpperCAmelCase,_UpperCAmelCase : Union[str, Any] = [0] * holes_range, [0] * holes_range # Make the sorting. for i in array: _UpperCAmelCase : Optional[int] = i - _min _UpperCAmelCase : Any = i holes_repeat[index] += 1 # Makes the array back by replacing the numbers. _UpperCAmelCase : List[Any] = 0 for i in range(snake_case__ ): while holes_repeat[i] > 0: _UpperCAmelCase : Optional[Any] = holes[i] index += 1 holes_repeat[i] -= 1 # Returns the sorted array. return array if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE__ : Dict = input('Enter numbers separated by comma:\n') SCREAMING_SNAKE_CASE__ : Optional[int] = [int(x) for x in user_input.split(',')] print(pigeon_sort(unsorted))
643
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A_ = { "configuration_canine": ["CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP", "CanineConfig"], "tokenization_canine": ["CanineTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ "CANINE_PRETRAINED_MODEL_ARCHIVE_LIST", "CanineForMultipleChoice", "CanineForQuestionAnswering", "CanineForSequenceClassification", "CanineForTokenClassification", "CanineLayer", "CanineModel", "CaninePreTrainedModel", "load_tf_weights_in_canine", ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys A_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
384
'''simple docstring''' def _UpperCamelCase ( __UpperCamelCase = 1 ,__UpperCamelCase = 10_00 ) -> int: lowerCamelCase_ = 1 lowerCamelCase_ = 0 for divide_by_number in range(__UpperCamelCase ,digit + 1 ): lowerCamelCase_ = [] lowerCamelCase_ = numerator for _ in range(1 ,digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(__UpperCamelCase ): lowerCamelCase_ = len(__UpperCamelCase ) lowerCamelCase_ = divide_by_number else: has_been_divided.append(__UpperCamelCase ) lowerCamelCase_ = now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
384
1
"""simple docstring""" import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class __A ( SCREAMING_SNAKE_CASE_ ): # to overwrite at feature extractactor specific tests UpperCAmelCase__ = None UpperCAmelCase__ = None @property def lowerCamelCase__ ( self : Dict ) -> Any: return self.feat_extract_tester.prepare_feat_extract_dict() def lowerCamelCase__ ( self : List[Any] ) -> Any: __magic_name__: Dict = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(__snake_case , """feature_size""" ) ) self.assertTrue(hasattr(__snake_case , """sampling_rate""" ) ) self.assertTrue(hasattr(__snake_case , """padding_value""" ) ) def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: __magic_name__: List[Any] = self.feat_extract_tester.prepare_inputs_for_common() __magic_name__: List[str] = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__: str = feat_extract.model_input_names[0] __magic_name__: Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(__snake_case ) == len(__snake_case ) for x, y in zip(__snake_case , processed_features[input_name] ) ) ) __magic_name__: List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__snake_case ) __magic_name__: str = BatchFeature({input_name: speech_inputs} , tensor_type="""np""" ) __magic_name__: List[str] = processed_features[input_name] if len(batch_features_input.shape ) < 3: __magic_name__: Optional[int] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def lowerCamelCase__ ( self : Tuple ) -> List[Any]: __magic_name__: Tuple = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__snake_case ) __magic_name__: Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__: Dict = feat_extract.model_input_names[0] __magic_name__: Optional[int] = BatchFeature({input_name: speech_inputs} , tensor_type="""pt""" ) __magic_name__: Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: __magic_name__: int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def lowerCamelCase__ ( self : Optional[int] ) -> Optional[int]: __magic_name__: Dict = self.feat_extract_tester.prepare_inputs_for_common(equal_length=__snake_case ) __magic_name__: Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__: Optional[Any] = feat_extract.model_input_names[0] __magic_name__: Tuple = BatchFeature({input_name: speech_inputs} , tensor_type="""tf""" ) __magic_name__: Optional[int] = processed_features[input_name] if len(batch_features_input.shape ) < 3: __magic_name__: Any = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def lowerCamelCase__ ( self : Optional[Any] , __snake_case : Optional[Any]=False ) -> Any: def _inputs_have_equal_length(__snake_case : int ): __magic_name__: Union[str, Any] = len(input[0] ) for input_slice in input[1:]: if len(__snake_case ) != length: return False return True def _inputs_are_equal(__snake_case : Tuple , __snake_case : List[str] ): if len(__snake_case ) != len(__snake_case ): return False for input_slice_a, input_slice_a in zip(__snake_case , __snake_case ): if not np.allclose(np.asarray(__snake_case ) , np.asarray(__snake_case ) , atol=1E-3 ): return False return True __magic_name__: str = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__: Any = self.feat_extract_tester.prepare_inputs_for_common(numpify=__snake_case ) __magic_name__: Tuple = feat_extract.model_input_names[0] __magic_name__: Tuple = BatchFeature({input_name: speech_inputs} ) __magic_name__: List[str] = self.feat_extract_tester.seq_length_diff __magic_name__: Optional[Any] = self.feat_extract_tester.max_seq_length + pad_diff __magic_name__: Tuple = self.feat_extract_tester.min_seq_length __magic_name__: List[str] = self.feat_extract_tester.batch_size __magic_name__: int = self.feat_extract_tester.feature_size # test padding for List[int] + numpy __magic_name__: Union[str, Any] = feat_extract.pad(__snake_case , padding=__snake_case ) __magic_name__: Optional[Any] = input_a[input_name] __magic_name__: str = feat_extract.pad(__snake_case , padding="""longest""" ) __magic_name__: str = input_a[input_name] __magic_name__: Optional[int] = feat_extract.pad(__snake_case , padding="""max_length""" , max_length=len(speech_inputs[-1] ) ) __magic_name__: Any = input_a[input_name] __magic_name__: str = feat_extract.pad(__snake_case , padding="""longest""" , return_tensors="""np""" ) __magic_name__: Any = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , padding="""max_length""" )[input_name] __magic_name__: Union[str, Any] = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=__snake_case , return_tensors="""np""" ) __magic_name__: Tuple = input_a[input_name] self.assertFalse(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_are_equal(__snake_case , __snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy __magic_name__: Optional[int] = feat_extract.pad(__snake_case , pad_to_multiple_of=1_0 ) __magic_name__: int = input_a[input_name] __magic_name__: Tuple = feat_extract.pad(__snake_case , padding="""longest""" , pad_to_multiple_of=1_0 ) __magic_name__: List[Any] = input_a[input_name] __magic_name__: Tuple = feat_extract.pad( __snake_case , padding="""max_length""" , pad_to_multiple_of=1_0 , max_length=__snake_case ) __magic_name__: int = input_a[input_name] __magic_name__: Tuple = feat_extract.pad( __snake_case , padding="""max_length""" , pad_to_multiple_of=1_0 , max_length=__snake_case , return_tensors="""np""" , ) __magic_name__: List[Any] = input_a[input_name] self.assertTrue(all(len(__snake_case ) % 1_0 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(__snake_case , __snake_case ) ) __magic_name__: Tuple = pad_max_length if pad_max_length % 1_0 == 0 else (pad_max_length // 1_0 + 1) * 1_0 self.assertTrue(all(len(__snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] , (batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct __magic_name__: Optional[int] = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def lowerCamelCase__ ( self : Any , __snake_case : Optional[int]=False ) -> Optional[Any]: def _inputs_have_equal_length(__snake_case : Union[str, Any] ): __magic_name__: Tuple = len(input[0] ) for input_slice in input[1:]: if len(__snake_case ) != length: return False return True def _inputs_are_equal(__snake_case : List[str] , __snake_case : Optional[int] ): if len(__snake_case ) != len(__snake_case ): return False for input_slice_a, input_slice_a in zip(__snake_case , __snake_case ): if not np.allclose(np.asarray(__snake_case ) , np.asarray(__snake_case ) , atol=1E-3 ): return False return True __magic_name__: List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__: List[str] = self.feat_extract_tester.prepare_inputs_for_common(numpify=__snake_case ) __magic_name__: str = feat_extract.model_input_names[0] __magic_name__: Optional[int] = BatchFeature({input_name: speech_inputs} ) # truncate to smallest __magic_name__: Optional[int] = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=len(speech_inputs[0] ) , truncation=__snake_case ) __magic_name__: int = input_a[input_name] __magic_name__: Optional[int] = feat_extract.pad(__snake_case , padding="""max_length""" , max_length=len(speech_inputs[0] ) ) __magic_name__: Dict = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertFalse(_inputs_have_equal_length(__snake_case ) ) # truncate to smallest with np __magic_name__: Union[str, Any] = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=len(speech_inputs[0] ) , return_tensors="""np""" , truncation=__snake_case , ) __magic_name__: Optional[Any] = input_a[input_name] __magic_name__: Dict = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=len(speech_inputs[0] ) , return_tensors="""np""" ) __magic_name__: Optional[Any] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__snake_case ) ) # truncate to middle __magic_name__: List[str] = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=len(speech_inputs[1] ) , truncation=__snake_case , return_tensors="""np""" , ) __magic_name__: Tuple = input_a[input_name] __magic_name__: Optional[int] = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=len(speech_inputs[1] ) , truncation=__snake_case ) __magic_name__: Any = input_a[input_name] __magic_name__: Tuple = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=len(speech_inputs[1] ) , return_tensors="""np""" ) __magic_name__: Tuple = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(_inputs_are_equal(__snake_case , __snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(__snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , truncation=__snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , padding="""longest""" , truncation=__snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , padding="""longest""" , truncation=__snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(__snake_case ): feat_extract.pad(__snake_case , padding="""max_length""" , truncation=__snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy __magic_name__: Tuple = 1_2 __magic_name__: Optional[Any] = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=__snake_case , truncation=__snake_case , ) __magic_name__: Tuple = input_a[input_name] __magic_name__: List[str] = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=__snake_case , ) __magic_name__: Optional[Any] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of __magic_name__: List[Any] = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: __magic_name__: List[Any] = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(__snake_case ) ) self.assertFalse(_inputs_have_equal_length(__snake_case ) ) def lowerCamelCase__ ( self : Tuple ) -> Optional[int]: self._check_padding(numpify=__snake_case ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Dict: self._check_padding(numpify=__snake_case ) def lowerCamelCase__ ( self : Optional[int] ) -> int: self._check_truncation(numpify=__snake_case ) def lowerCamelCase__ ( self : int ) -> int: self._check_truncation(numpify=__snake_case ) @require_torch def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: __magic_name__: List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__: Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() __magic_name__: Optional[int] = feat_extract.model_input_names[0] __magic_name__: Optional[Any] = BatchFeature({input_name: speech_inputs} ) __magic_name__: List[Any] = feat_extract.pad(__snake_case , padding="""longest""" , return_tensors="""np""" )[input_name] __magic_name__: Any = feat_extract.pad(__snake_case , padding="""longest""" , return_tensors="""pt""" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def lowerCamelCase__ ( self : Union[str, Any] ) -> int: __magic_name__: Dict = self.feature_extraction_class(**self.feat_extract_dict ) __magic_name__: str = self.feat_extract_tester.prepare_inputs_for_common() __magic_name__: Any = feat_extract.model_input_names[0] __magic_name__: Union[str, Any] = BatchFeature({input_name: speech_inputs} ) __magic_name__: int = feat_extract.pad(__snake_case , padding="""longest""" , return_tensors="""np""" )[input_name] __magic_name__: Tuple = feat_extract.pad(__snake_case , padding="""longest""" , return_tensors="""tf""" )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def lowerCamelCase__ ( self : Union[str, Any] ) -> int: __magic_name__: Optional[Any] = self.feat_extract_dict __magic_name__: Optional[Any] = True __magic_name__: List[str] = self.feature_extraction_class(**__snake_case ) __magic_name__: List[str] = self.feat_extract_tester.prepare_inputs_for_common() __magic_name__: Union[str, Any] = [len(__snake_case ) for x in speech_inputs] __magic_name__: int = feat_extract.model_input_names[0] __magic_name__: List[str] = BatchFeature({input_name: speech_inputs} ) __magic_name__: Tuple = feat_extract.pad(__snake_case , padding="""longest""" , return_tensors="""np""" ) self.assertIn("""attention_mask""" , __snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , __snake_case ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Tuple: __magic_name__: Any = self.feat_extract_dict __magic_name__: Optional[Any] = True __magic_name__: str = self.feature_extraction_class(**__snake_case ) __magic_name__: Optional[Any] = self.feat_extract_tester.prepare_inputs_for_common() __magic_name__: str = [len(__snake_case ) for x in speech_inputs] __magic_name__: Union[str, Any] = feat_extract.model_input_names[0] __magic_name__: Optional[int] = BatchFeature({input_name: speech_inputs} ) __magic_name__: Union[str, Any] = min(__snake_case ) __magic_name__: Dict = feat_extract.pad( __snake_case , padding="""max_length""" , max_length=__snake_case , truncation=__snake_case , return_tensors="""np""" ) self.assertIn("""attention_mask""" , __snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
96
"""simple docstring""" def a ( __UpperCAmelCase : List[Any] ) -> str: __magic_name__: Optional[int] = [0] * len(__UpperCAmelCase ) __magic_name__: str = [] __magic_name__: Any = [] __magic_name__: Union[str, Any] = 0 for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__UpperCAmelCase ) ): if indegree[i] == 0: queue.append(__UpperCAmelCase ) while queue: __magic_name__: Optional[Any] = queue.pop(0 ) cnt += 1 topo.append(__UpperCAmelCase ) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(__UpperCAmelCase ) if cnt != len(__UpperCAmelCase ): print("""Cycle exists""" ) else: print(__UpperCAmelCase ) # Adjacency List of Graph __lowerCamelCase = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topological_sort(graph)
96
1
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor _lowerCamelCase : Dict = logging.get_logger(__name__) class lowerCAmelCase__ ( __magic_name__ ): '''simple docstring''' def __init__( self , *lowercase__ , **lowercase__ ): '''simple docstring''' warnings.warn( '''The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use VideoMAEImageProcessor instead.''' , lowercase__ , ) super().__init__(*lowercase__ , **lowercase__ )
516
# coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # 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. # this script dumps information about the environment import os import platform import sys _lowerCamelCase : str = '''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
516
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase__ : int = logging.get_logger(__name__) lowerCamelCase__ : str = { "studio-ousia/luke-base": "https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json", "studio-ousia/luke-large": "https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json", } class lowercase__( _UpperCAmelCase ): '''simple docstring''' UpperCamelCase = """luke""" def __init__( self :List[Any] , lowerCamelCase_ :Optional[int]=5_02_67 , lowerCamelCase_ :List[Any]=50_00_00 , lowerCamelCase_ :str=7_68 , lowerCamelCase_ :Optional[Any]=2_56 , lowerCamelCase_ :List[Any]=12 , lowerCamelCase_ :List[Any]=12 , lowerCamelCase_ :Any=30_72 , lowerCamelCase_ :Optional[int]="gelu" , lowerCamelCase_ :Dict=0.1 , lowerCamelCase_ :Any=0.1 , lowerCamelCase_ :str=5_12 , lowerCamelCase_ :Tuple=2 , lowerCamelCase_ :Optional[Any]=0.0_2 , lowerCamelCase_ :Optional[int]=1E-12 , lowerCamelCase_ :Tuple=True , lowerCamelCase_ :int=None , lowerCamelCase_ :Dict=1 , lowerCamelCase_ :str=0 , lowerCamelCase_ :int=2 , **lowerCamelCase_ :List[str] , ) -> int: '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , **lowerCamelCase_ ) SCREAMING_SNAKE_CASE : str = vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = entity_vocab_size SCREAMING_SNAKE_CASE : int = hidden_size SCREAMING_SNAKE_CASE : Dict = entity_emb_size SCREAMING_SNAKE_CASE : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : str = hidden_act SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Dict = type_vocab_size SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE : Optional[Any] = use_entity_aware_attention SCREAMING_SNAKE_CASE : str = classifier_dropout
698
"""simple docstring""" import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets lowerCamelCase__ : List[Any] = "\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" lowerCamelCase__ : List[str] = "\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" lowerCamelCase__ : List[Any] = "\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase__( datasets.Metric ): '''simple docstring''' def __lowerCAmelCase ( self :Optional[int] ) -> int: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/krishnap25/mauve''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , codebase_urls=['''https://github.com/krishnap25/mauve'''] , reference_urls=[ '''https://arxiv.org/abs/2102.01454''', '''https://github.com/krishnap25/mauve''', ] , ) def __lowerCAmelCase ( self :Union[str, Any] , lowerCamelCase_ :Optional[Any] , lowerCamelCase_ :List[str] , lowerCamelCase_ :Optional[Any]=None , lowerCamelCase_ :str=None , lowerCamelCase_ :Tuple=None , lowerCamelCase_ :Optional[Any]=None , lowerCamelCase_ :Optional[int]="auto" , lowerCamelCase_ :Dict=-1 , lowerCamelCase_ :str=0.9 , lowerCamelCase_ :str=5 , lowerCamelCase_ :Tuple=5_00 , lowerCamelCase_ :str="gpt2-large" , lowerCamelCase_ :List[Any]=-1 , lowerCamelCase_ :Dict=10_24 , lowerCamelCase_ :Tuple=25 , lowerCamelCase_ :List[Any]=5 , lowerCamelCase_ :Dict=True , lowerCamelCase_ :List[Any]=25 , ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = compute_mauve( p_text=lowerCamelCase_ , q_text=lowerCamelCase_ , p_features=lowerCamelCase_ , q_features=lowerCamelCase_ , p_tokens=lowerCamelCase_ , q_tokens=lowerCamelCase_ , num_buckets=lowerCamelCase_ , pca_max_data=lowerCamelCase_ , kmeans_explained_var=lowerCamelCase_ , kmeans_num_redo=lowerCamelCase_ , kmeans_max_iter=lowerCamelCase_ , featurize_model_name=lowerCamelCase_ , device_id=lowerCamelCase_ , max_text_length=lowerCamelCase_ , divergence_curve_discretization_size=lowerCamelCase_ , mauve_scaling_factor=lowerCamelCase_ , verbose=lowerCamelCase_ , seed=lowerCamelCase_ , ) return out
698
1
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record __A : List[str] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' __A : List[Any] = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' __A : Any = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def __UpperCamelCase ( _A : str , _A : int ) ->List[str]: """simple docstring""" return float((preds == labels).mean() ) def __UpperCamelCase ( _A : Any , _A : Union[str, Any] , _A : Any="binary" ) ->Union[str, Any]: """simple docstring""" lowerCamelCase_ =simple_accuracy(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowerCamelCase_ =float(fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=__SCREAMING_SNAKE_CASE , average=__SCREAMING_SNAKE_CASE ) ) return { "accuracy": acc, "f1": fa, } def __UpperCamelCase ( _A : Union[str, Any] , _A : Dict ) ->List[str]: """simple docstring""" lowerCamelCase_ ={} for id_pred, label in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): lowerCamelCase_ =f'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' lowerCamelCase_ =id_pred["""prediction"""] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowerCamelCase_ =[(pred, label)] lowerCamelCase_ , lowerCamelCase_ =[], [] for question, preds_labels in question_map.items(): lowerCamelCase_ , lowerCamelCase_ =zip(*__SCREAMING_SNAKE_CASE ) lowerCamelCase_ =fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=__SCREAMING_SNAKE_CASE , average="""macro""" ) fas.append(__SCREAMING_SNAKE_CASE ) lowerCamelCase_ =int(sum(pred == label for pred, label in preds_labels ) == len(__SCREAMING_SNAKE_CASE ) ) ems.append(__SCREAMING_SNAKE_CASE ) lowerCamelCase_ =float(sum(__SCREAMING_SNAKE_CASE ) / len(__SCREAMING_SNAKE_CASE ) ) lowerCamelCase_ =sum(__SCREAMING_SNAKE_CASE ) / len(__SCREAMING_SNAKE_CASE ) lowerCamelCase_ =float(fa_score(y_true=__SCREAMING_SNAKE_CASE , y_pred=[id_pred["""prediction"""] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class _SCREAMING_SNAKE_CASE ( datasets.Metric): def _snake_case ( self )-> int: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format="""numpy""" if not self.config_name == """record""" and not self.config_name == """multirc""" else None , ) def _snake_case ( self )-> List[str]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "prediction_text": datasets.Value("""string""" ), }, "references": { "idx": { "passage": datasets.Value("""int64""" ), "query": datasets.Value("""int64""" ), }, "answers": datasets.Sequence(datasets.Value("""string""" ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value("""int64""" ), "paragraph": datasets.Value("""int64""" ), "question": datasets.Value("""int64""" ), }, "prediction": datasets.Value("""int64""" ), }, "references": datasets.Value("""int64""" ), } else: return { "predictions": datasets.Value("""int64""" ), "references": datasets.Value("""int64""" ), } def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )-> Dict: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} elif self.config_name == "cb": return acc_and_fa(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , fa_avg="""macro""" ) elif self.config_name == "record": lowerCamelCase_ =[ { """qas""": [ {"""id""": ref["""idx"""]["""query"""], """answers""": [{"""text""": ans} for ans in ref["""answers"""]]} for ref in references ] } ] lowerCamelCase_ ={pred["""idx"""]["""query"""]: pred["""prediction_text"""] for pred in predictions} return evaluate_record(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[0] elif self.config_name == "multirc": return evaluate_multirc(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )} else: raise KeyError( """You should supply a configuration name selected in """ """[\"boolq\", \"cb\", \"copa\", \"multirc\", \"record\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"axb\", \"axg\",]""" )
701
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig __A : int = { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/config.json', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/config.json', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/config.json', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/config.json', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/config.json', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/config.json', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json', } class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): _UpperCamelCase:Any = "albert" def __init__( self , _SCREAMING_SNAKE_CASE=3_0000 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=4096 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=64 , _SCREAMING_SNAKE_CASE=1_6384 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=1E-12 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , **_SCREAMING_SNAKE_CASE , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =vocab_size lowerCamelCase_ =embedding_size lowerCamelCase_ =hidden_size lowerCamelCase_ =num_hidden_layers lowerCamelCase_ =num_hidden_groups lowerCamelCase_ =num_attention_heads lowerCamelCase_ =inner_group_num lowerCamelCase_ =hidden_act lowerCamelCase_ =intermediate_size lowerCamelCase_ =hidden_dropout_prob lowerCamelCase_ =attention_probs_dropout_prob lowerCamelCase_ =max_position_embeddings lowerCamelCase_ =type_vocab_size lowerCamelCase_ =initializer_range lowerCamelCase_ =layer_norm_eps lowerCamelCase_ =classifier_dropout_prob lowerCamelCase_ =position_embedding_type class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): @property def _snake_case ( self )-> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": lowerCamelCase_ ={0: """batch""", 1: """choice""", 2: """sequence"""} else: lowerCamelCase_ ={0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
75
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a = logging.get_logger(__name__) a = { '''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config.json''', } class lowercase_ ( __lowerCAmelCase ): '''simple docstring''' UpperCAmelCase : Optional[int] = '''transfo-xl''' UpperCAmelCase : Union[str, Any] = ['''mems'''] UpperCAmelCase : Dict = { '''n_token''': '''vocab_size''', '''hidden_size''': '''d_model''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : Dict , _UpperCAmelCase : int=267_735 , _UpperCAmelCase : Union[str, Any]=[20_000, 40_000, 200_000] , _UpperCAmelCase : Union[str, Any]=1_024 , _UpperCAmelCase : Any=1_024 , _UpperCAmelCase : int=16 , _UpperCAmelCase : Optional[Any]=64 , _UpperCAmelCase : Optional[Any]=4_096 , _UpperCAmelCase : Optional[int]=4 , _UpperCAmelCase : List[Any]=False , _UpperCAmelCase : Tuple=18 , _UpperCAmelCase : Dict=1_600 , _UpperCAmelCase : int=1_000 , _UpperCAmelCase : Any=True , _UpperCAmelCase : List[Any]=True , _UpperCAmelCase : int=0 , _UpperCAmelCase : Union[str, Any]=-1 , _UpperCAmelCase : Any=True , _UpperCAmelCase : Any=0.1 , _UpperCAmelCase : Any=0.0 , _UpperCAmelCase : Optional[Any]=True , _UpperCAmelCase : Dict="normal" , _UpperCAmelCase : List[str]=0.01 , _UpperCAmelCase : Dict=0.01 , _UpperCAmelCase : Union[str, Any]=0.02 , _UpperCAmelCase : str=1E-5 , _UpperCAmelCase : Dict=0 , **_UpperCAmelCase : Any , ): _A = vocab_size _A = [] self.cutoffs.extend(_UpperCAmelCase ) if proj_share_all_but_first: _A = [False] + [True] * len(self.cutoffs ) else: _A = [False] + [False] * len(self.cutoffs ) _A = d_model _A = d_embed _A = d_head _A = d_inner _A = div_val _A = pre_lnorm _A = n_layer _A = n_head _A = mem_len _A = same_length _A = attn_type _A = clamp_len _A = sample_softmax _A = adaptive _A = dropout _A = dropatt _A = untie_r _A = init _A = init_range _A = proj_init_std _A = init_std _A = layer_norm_epsilon super().__init__(eos_token_id=_UpperCAmelCase , **_UpperCAmelCase ) @property def lowerCAmelCase_ ( self : Optional[int] ): # Message copied from Transformer-XL documentation logger.info(F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) return -1 @max_position_embeddings.setter def lowerCAmelCase_ ( self : List[str] , _UpperCAmelCase : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
7
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ) -> Optional[Any]: '''simple docstring''' def wrapper(*_UpperCAmelCase, **_UpperCAmelCase ): lowerCAmelCase : str = timeit.default_timer() lowerCAmelCase : str = func(*_UpperCAmelCase, **_UpperCAmelCase ) lowerCAmelCase : Optional[int] = timeit.default_timer() - starttime return delta lowerCAmelCase : Union[str, Any] = func.__name__ return wrapper def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase=100, _UpperCAmelCase=None ) -> Any: '''simple docstring''' lowerCAmelCase : Dict = [] lowerCAmelCase : Optional[int] = seq_shapes or {} for i in range(_UpperCAmelCase ): lowerCAmelCase : Any = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(_UpperCAmelCase, _ArrayXD ): lowerCAmelCase : Dict = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(_UpperCAmelCase, datasets.Value ): if v.dtype == "string": lowerCAmelCase : Any = 'The small grey turtle was surprisingly fast when challenged.' else: lowerCAmelCase : Optional[Any] = np.random.randint(10, size=1 ).astype(v.dtype ).item() elif isinstance(_UpperCAmelCase, datasets.Sequence ): while isinstance(_UpperCAmelCase, datasets.Sequence ): lowerCAmelCase : int = v.feature lowerCAmelCase : Optional[int] = seq_shapes[k] lowerCAmelCase : str = np.random.rand(*_UpperCAmelCase ).astype(v.dtype ) lowerCAmelCase : Any = data dummy_data.append((i, example) ) return dummy_data def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase, _UpperCAmelCase=100, _UpperCAmelCase=None ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase : Any = generate_examples(_UpperCAmelCase, num_examples=_UpperCAmelCase, seq_shapes=_UpperCAmelCase ) with ArrowWriter(features=_UpperCAmelCase, path=_UpperCAmelCase ) as writer: for key, record in dummy_data: lowerCAmelCase : Any = features.encode_example(_UpperCAmelCase ) writer.write(_UpperCAmelCase ) lowerCAmelCase , lowerCAmelCase : Optional[int] = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f"Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}." ) lowerCAmelCase : int = datasets.Dataset.from_file(filename=_UpperCAmelCase, info=datasets.DatasetInfo(features=_UpperCAmelCase ) ) return dataset
343
0
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path _snake_case : Dict = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) _snake_case : List[Any] = [ord(letter) for letter in string.ascii_lowercase] _snake_case : Optional[Any] = {ord(char) for char in VALID_CHARS} _snake_case : int = ['the', 'be', 'to', 'of', 'and', 'in', 'that', 'have'] def A__ ( UpperCamelCase , UpperCamelCase ): A = "" A = 42 A = 42 A = 42 for keychar, cipherchar in zip(cycle(snake_case__ ) , snake_case__ ): A = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(snake_case__ ) return decoded def A__ ( UpperCamelCase ): A = [] for key in product(snake_case__ , repeat=3 ): A = try_key(snake_case__ , snake_case__ ) if encoded is not None: possibles.append(snake_case__ ) return possibles def A__ ( UpperCamelCase , UpperCamelCase ): return [possible for possible in possibles if common_word in possible.lower()] def A__ ( UpperCamelCase = "p059_cipher.txt" ): A = 42 A = 42 A = 42 A = 42 A = Path(snake_case__ ).parent.joinpath(snake_case__ ).read_text(encoding="utf-8" ) A = [int(snake_case__ ) for number in data.strip().split("," )] A = filter_valid_chars(snake_case__ ) for common_word in COMMON_WORDS: A = filter_common_word(snake_case__ , snake_case__ ) if len(snake_case__ ) == 1: break A = possibles[0] return sum(ord(snake_case__ ) for char in decoded_text ) if __name__ == "__main__": print(F"""{solution() = }""")
706
"""simple docstring""" import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig _snake_case : Tuple = logging.get_logger(__name__) _snake_case : Union[str, Any] = 'T5Config' def A__ ( UpperCamelCase , UpperCamelCase , UpperCamelCase ): A = jnp.zeros_like(UpperCamelCase ) A = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) A = shifted_input_ids.at[:, 0].set(UpperCamelCase ) A = jnp.where(shifted_input_ids == -100 , UpperCamelCase , UpperCamelCase ) return shifted_input_ids class _UpperCAmelCase ( lowercase_ ): UpperCamelCase = '''mt5''' UpperCamelCase = MTaConfig class _UpperCAmelCase ( lowercase_ ): UpperCamelCase = '''mt5''' UpperCamelCase = MTaConfig class _UpperCAmelCase ( lowercase_ ): UpperCamelCase = '''mt5''' UpperCamelCase = MTaConfig
524
0
# 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. from argparse import ArgumentParser from accelerate.commands.config import get_config_parser from accelerate.commands.env import env_command_parser from accelerate.commands.launch import launch_command_parser from accelerate.commands.test import test_command_parser from accelerate.commands.tpu import tpu_command_parser def _UpperCamelCase (): """simple docstring""" UpperCamelCase__ = ArgumentParser("""Accelerate CLI tool""" , usage="""accelerate <command> [<args>]""" , allow_abbrev=lowerCamelCase__ ) UpperCamelCase__ = parser.add_subparsers(help="""accelerate command helpers""" ) # Register commands get_config_parser(subparsers=lowerCamelCase__ ) env_command_parser(subparsers=lowerCamelCase__ ) launch_command_parser(subparsers=lowerCamelCase__ ) tpu_command_parser(subparsers=lowerCamelCase__ ) test_command_parser(subparsers=lowerCamelCase__ ) # Let's go UpperCamelCase__ = parser.parse_args() if not hasattr(lowerCamelCase__ , """func""" ): parser.print_help() exit(1 ) # Run args.func(lowerCamelCase__ ) if __name__ == "__main__": main()
619
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu 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 ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class _SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , snake_case_ , unittest.TestCase ): lowerCAmelCase__ = StableDiffusionControlNetImgaImgPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'} lowerCAmelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'control_image'} ) lowerCAmelCase__ = IMAGE_TO_IMAGE_IMAGE_PARAMS def SCREAMING_SNAKE_CASE_( self ) -> int: torch.manual_seed(0 ) lowerCamelCase_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) lowerCamelCase_ = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) lowerCamelCase_ = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCamelCase_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) lowerCamelCase_ = CLIPTextModel(lowercase ) lowerCamelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCamelCase_ = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=0 ) -> int: if str(lowercase ).startswith("mps" ): lowerCamelCase_ = torch.manual_seed(lowercase ) else: lowerCamelCase_ = torch.Generator(device=lowercase ).manual_seed(lowercase ) lowerCamelCase_ = 2 lowerCamelCase_ = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=lowercase , device=torch.device(lowercase ) , ) lowerCamelCase_ = floats_tensor(control_image.shape , rng=random.Random(lowercase ) ).to(lowercase ) lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ = Image.fromarray(np.uinta(lowercase ) ).convert("RGB" ).resize((64, 64) ) lowerCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def SCREAMING_SNAKE_CASE_( self ) -> List[str]: return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def SCREAMING_SNAKE_CASE_( self ) -> List[str]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def SCREAMING_SNAKE_CASE_( self ) -> Any: self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) class _SCREAMING_SNAKE_CASE ( snake_case_ , snake_case_ , unittest.TestCase ): lowerCAmelCase__ = StableDiffusionControlNetImgaImgPipeline lowerCAmelCase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width'} lowerCAmelCase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase__ = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def SCREAMING_SNAKE_CASE_( self ) -> Dict: torch.manual_seed(0 ) lowerCamelCase_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(lowercase ): if isinstance(lowercase , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) lowerCamelCase_ = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(lowercase ) torch.manual_seed(0 ) lowerCamelCase_ = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(lowercase ) torch.manual_seed(0 ) lowerCamelCase_ = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCamelCase_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) lowerCamelCase_ = CLIPTextModel(lowercase ) lowerCamelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCamelCase_ = MultiControlNetModel([controlneta, controlneta] ) lowerCamelCase_ = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def SCREAMING_SNAKE_CASE_( self , lowercase , lowercase=0 ) -> List[Any]: if str(lowercase ).startswith("mps" ): lowerCamelCase_ = torch.manual_seed(lowercase ) else: lowerCamelCase_ = torch.Generator(device=lowercase ).manual_seed(lowercase ) lowerCamelCase_ = 2 lowerCamelCase_ = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=lowercase , device=torch.device(lowercase ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=lowercase , device=torch.device(lowercase ) , ), ] lowerCamelCase_ = floats_tensor(control_image[0].shape , rng=random.Random(lowercase ) ).to(lowercase ) lowerCamelCase_ = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase_ = Image.fromarray(np.uinta(lowercase ) ).convert("RGB" ).resize((64, 64) ) lowerCamelCase_ = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = self.pipeline_class(**lowercase ) pipe.to(lowercase ) lowerCamelCase_ = 1_0.0 lowerCamelCase_ = 4 lowerCamelCase_ = self.get_dummy_inputs(lowercase ) lowerCamelCase_ = steps lowerCamelCase_ = scale lowerCamelCase_ = pipe(**lowercase )[0] lowerCamelCase_ = self.get_dummy_inputs(lowercase ) lowerCamelCase_ = steps lowerCamelCase_ = scale lowerCamelCase_ = pipe(**lowercase , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] lowerCamelCase_ = self.get_dummy_inputs(lowercase ) lowerCamelCase_ = steps lowerCamelCase_ = scale lowerCamelCase_ = pipe(**lowercase , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] lowerCamelCase_ = self.get_dummy_inputs(lowercase ) lowerCamelCase_ = steps lowerCamelCase_ = scale lowerCamelCase_ = pipe(**lowercase , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 def SCREAMING_SNAKE_CASE_( self ) -> Dict: return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def SCREAMING_SNAKE_CASE_( self ) -> Union[str, Any]: self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) def SCREAMING_SNAKE_CASE_( self ) -> int: lowerCamelCase_ = self.get_dummy_components() lowerCamelCase_ = self.pipeline_class(**lowercase ) pipe.to(lowercase ) pipe.set_progress_bar_config(disable=lowercase ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(lowercase ) except NotImplementedError: pass @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_( self ) -> List[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: lowerCamelCase_ = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) lowerCamelCase_ = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=lowercase , controlnet=lowercase ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=lowercase ) lowerCamelCase_ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCamelCase_ = "evil space-punk bird" lowerCamelCase_ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) lowerCamelCase_ = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) lowerCamelCase_ = pipe( lowercase , lowercase , control_image=lowercase , generator=lowercase , output_type="np" , num_inference_steps=50 , strength=0.6 , ) lowerCamelCase_ = output.images[0] assert image.shape == (512, 512, 3) lowerCamelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy" ) assert np.abs(expected_image - image ).max() < 9e-2
463
0
'''simple docstring''' def __UpperCAmelCase ( _UpperCAmelCase : int = 10 ) -> str: if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) or n < 0: raise ValueError("Invalid input" ) __snake_case = 10**n __snake_case = 2_84_33 * (pow(2 , 7_83_04_57 , _UpperCAmelCase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F'''{solution(10) = }''')
717
'''simple docstring''' import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def __UpperCAmelCase ( _UpperCAmelCase : Dict ) -> int: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def __UpperCAmelCase ( ) -> Dict: with parallel_backend("spark" ): assert ParallelBackendConfig.backend_name == "spark" __snake_case = [1, 2, 3] with pytest.raises(_UpperCAmelCase ): with parallel_backend("unsupported backend" ): map_nested(_UpperCAmelCase , _UpperCAmelCase , num_proc=2 ) with pytest.raises(_UpperCAmelCase ): with parallel_backend("unsupported backend" ): map_nested(_UpperCAmelCase , _UpperCAmelCase , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("num_proc" , [2, -1] ) def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] ) -> Optional[int]: __snake_case = [1, 2] __snake_case = {"a": 1, "b": 2} __snake_case = {"a": [1, 2], "b": [3, 4]} __snake_case = {"a": {"1": 1}, "b": 2} __snake_case = {"a": 1, "b": 2, "c": 3, "d": 4} __snake_case = [2, 3] __snake_case = {"a": 2, "b": 3} __snake_case = {"a": [2, 3], "b": [4, 5]} __snake_case = {"a": {"1": 2}, "b": 3} __snake_case = {"a": 2, "b": 3, "c": 4, "d": 5} with parallel_backend("spark" ): assert map_nested(_UpperCAmelCase , _UpperCAmelCase , num_proc=_UpperCAmelCase ) == expected_map_nested_sa assert map_nested(_UpperCAmelCase , _UpperCAmelCase , num_proc=_UpperCAmelCase ) == expected_map_nested_sa assert map_nested(_UpperCAmelCase , _UpperCAmelCase , num_proc=_UpperCAmelCase ) == expected_map_nested_sa assert map_nested(_UpperCAmelCase , _UpperCAmelCase , num_proc=_UpperCAmelCase ) == expected_map_nested_sa assert map_nested(_UpperCAmelCase , _UpperCAmelCase , num_proc=_UpperCAmelCase ) == expected_map_nested_sa
680
0
def lowercase_( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): '''simple docstring''' if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) lowerCamelCase : List[str] = str(bin(SCREAMING_SNAKE_CASE_ ) )[2:] # remove the leading "0b" lowerCamelCase : Any = str(bin(SCREAMING_SNAKE_CASE_ ) )[2:] # remove the leading "0b" lowerCamelCase : Optional[int] = max(len(SCREAMING_SNAKE_CASE_ ) , len(SCREAMING_SNAKE_CASE_ ) ) return "0b" + "".join( str(int(char_a != char_b ) ) for char_a, char_b in zip(a_binary.zfill(SCREAMING_SNAKE_CASE_ ) , b_binary.zfill(SCREAMING_SNAKE_CASE_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
340
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _snake_case = {'''LayoutLMv2Config''', '''LayoutLMv3Config'''} @is_pipeline_test class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' __A : Tuple = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __A : List[str] = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __A : Any = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __A : Optional[Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def _snake_case ( self , __A , __A , __A ): """simple docstring""" lowerCamelCase : Any = ZeroShotClassificationPipeline( model=__A , tokenizer=__A , candidate_labels=["polics", "health"] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def _snake_case ( self , __A , __A ): """simple docstring""" lowerCamelCase : List[str] = classifier("Who are you voting for in 2020?" , candidate_labels="politics" ) self.assertEqual(__A , {"sequence": ANY(__A ), "labels": [ANY(__A )], "scores": [ANY(__A )]} ) # No kwarg lowerCamelCase : str = classifier("Who are you voting for in 2020?" , ["politics"] ) self.assertEqual(__A , {"sequence": ANY(__A ), "labels": [ANY(__A )], "scores": [ANY(__A )]} ) lowerCamelCase : str = classifier("Who are you voting for in 2020?" , candidate_labels=["politics"] ) self.assertEqual(__A , {"sequence": ANY(__A ), "labels": [ANY(__A )], "scores": [ANY(__A )]} ) lowerCamelCase : Optional[int] = classifier("Who are you voting for in 2020?" , candidate_labels="politics, public health" ) self.assertEqual( __A , {"sequence": ANY(__A ), "labels": [ANY(__A ), ANY(__A )], "scores": [ANY(__A ), ANY(__A )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["scores"] ) ) , 1.0 ) lowerCamelCase : str = classifier("Who are you voting for in 2020?" , candidate_labels=["politics", "public health"] ) self.assertEqual( __A , {"sequence": ANY(__A ), "labels": [ANY(__A ), ANY(__A )], "scores": [ANY(__A ), ANY(__A )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs["scores"] ) ) , 1.0 ) lowerCamelCase : List[str] = classifier( "Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template="This text is about {}" ) self.assertEqual(__A , {"sequence": ANY(__A ), "labels": [ANY(__A )], "scores": [ANY(__A )]} ) # https://github.com/huggingface/transformers/issues/13846 lowerCamelCase : str = classifier(["I am happy"] , ["positive", "negative"] ) self.assertEqual( __A , [ {"sequence": ANY(__A ), "labels": [ANY(__A ), ANY(__A )], "scores": [ANY(__A ), ANY(__A )]} for i in range(1 ) ] , ) lowerCamelCase : Union[str, Any] = classifier(["I am happy", "I am sad"] , ["positive", "negative"] ) self.assertEqual( __A , [ {"sequence": ANY(__A ), "labels": [ANY(__A ), ANY(__A )], "scores": [ANY(__A ), ANY(__A )]} for i in range(2 ) ] , ) with self.assertRaises(__A ): classifier("" , candidate_labels="politics" ) with self.assertRaises(__A ): classifier(__A , candidate_labels="politics" ) with self.assertRaises(__A ): classifier("Who are you voting for in 2020?" , candidate_labels="" ) with self.assertRaises(__A ): classifier("Who are you voting for in 2020?" , candidate_labels=__A ) with self.assertRaises(__A ): classifier( "Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template="Not formatting template" , ) with self.assertRaises(__A ): classifier( "Who are you voting for in 2020?" , candidate_labels="politics" , hypothesis_template=__A , ) self.run_entailment_id(__A ) def _snake_case ( self , __A ): """simple docstring""" lowerCamelCase : int = zero_shot_classifier.model.config lowerCamelCase : Optional[Any] = config.labelaid lowerCamelCase : Union[str, Any] = zero_shot_classifier.entailment_id lowerCamelCase : Tuple = {"LABEL_0": 0, "LABEL_1": 1, "LABEL_2": 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) lowerCamelCase : Any = {"entailment": 0, "neutral": 1, "contradiction": 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) lowerCamelCase : Optional[int] = {"ENTAIL": 0, "NON-ENTAIL": 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) lowerCamelCase : List[Any] = {"ENTAIL": 2, "NEUTRAL": 1, "CONTR": 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) lowerCamelCase : Any = original_labelaid self.assertEqual(__A , zero_shot_classifier.entailment_id ) @require_torch def _snake_case ( self ): """simple docstring""" lowerCamelCase : Union[str, Any] = pipeline( "zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="pt" , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( "Who are you voting for in 2020?" * 100 , candidate_labels=["politics", "public health", "science"] ) @require_torch def _snake_case ( self ): """simple docstring""" lowerCamelCase : List[str] = pipeline( "zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="pt" , ) lowerCamelCase : int = zero_shot_classifier( "Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] ) self.assertEqual( nested_simplify(__A ) , { "sequence": "Who are you voting for in 2020?", "labels": ["science", "public health", "politics"], "scores": [0.333, 0.333, 0.333], } , ) @require_tf def _snake_case ( self ): """simple docstring""" lowerCamelCase : Optional[Any] = pipeline( "zero-shot-classification" , model="sshleifer/tiny-distilbert-base-cased-distilled-squad" , framework="tf" , ) lowerCamelCase : Union[str, Any] = zero_shot_classifier( "Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] ) self.assertEqual( nested_simplify(__A ) , { "sequence": "Who are you voting for in 2020?", "labels": ["science", "public health", "politics"], "scores": [0.333, 0.333, 0.333], } , ) @slow @require_torch def _snake_case ( self ): """simple docstring""" lowerCamelCase : Tuple = pipeline("zero-shot-classification" , model="roberta-large-mnli" , framework="pt" ) lowerCamelCase : Tuple = zero_shot_classifier( "Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] ) self.assertEqual( nested_simplify(__A ) , { "sequence": "Who are you voting for in 2020?", "labels": ["politics", "public health", "science"], "scores": [0.976, 0.015, 0.009], } , ) lowerCamelCase : Union[str, Any] = zero_shot_classifier( "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks" " in an encoder-decoder configuration. The best performing models also connect the encoder and decoder" " through an attention mechanism. We propose a new simple network architecture, the Transformer, based" " solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two" " machine translation tasks show these models to be superior in quality while being more parallelizable" " and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014" " English-to-German translation task, improving over the existing best results, including ensembles by" " over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new" " single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small" " fraction of the training costs of the best models from the literature. We show that the Transformer" " generalizes well to other tasks by applying it successfully to English constituency parsing both with" " large and limited training data." , candidate_labels=["machine learning", "statistics", "translation", "vision"] , multi_label=__A , ) self.assertEqual( nested_simplify(__A ) , { "sequence": ( "The dominant sequence transduction models are based on complex recurrent or convolutional neural" " networks in an encoder-decoder configuration. The best performing models also connect the" " encoder and decoder through an attention mechanism. We propose a new simple network" " architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence" " and convolutions entirely. Experiments on two machine translation tasks show these models to be" " superior in quality while being more parallelizable and requiring significantly less time to" " train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task," " improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014" " English-to-French translation task, our model establishes a new single-model state-of-the-art" " BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training" " costs of the best models from the literature. We show that the Transformer generalizes well to" " other tasks by applying it successfully to English constituency parsing both with large and" " limited training data." ), "labels": ["translation", "machine learning", "vision", "statistics"], "scores": [0.817, 0.713, 0.018, 0.018], } , ) @slow @require_tf def _snake_case ( self ): """simple docstring""" lowerCamelCase : Dict = pipeline("zero-shot-classification" , model="roberta-large-mnli" , framework="tf" ) lowerCamelCase : Optional[int] = zero_shot_classifier( "Who are you voting for in 2020?" , candidate_labels=["politics", "public health", "science"] ) self.assertEqual( nested_simplify(__A ) , { "sequence": "Who are you voting for in 2020?", "labels": ["politics", "public health", "science"], "scores": [0.976, 0.015, 0.009], } , ) lowerCamelCase : List[Any] = zero_shot_classifier( "The dominant sequence transduction models are based on complex recurrent or convolutional neural networks" " in an encoder-decoder configuration. The best performing models also connect the encoder and decoder" " through an attention mechanism. We propose a new simple network architecture, the Transformer, based" " solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two" " machine translation tasks show these models to be superior in quality while being more parallelizable" " and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014" " English-to-German translation task, improving over the existing best results, including ensembles by" " over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new" " single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small" " fraction of the training costs of the best models from the literature. We show that the Transformer" " generalizes well to other tasks by applying it successfully to English constituency parsing both with" " large and limited training data." , candidate_labels=["machine learning", "statistics", "translation", "vision"] , multi_label=__A , ) self.assertEqual( nested_simplify(__A ) , { "sequence": ( "The dominant sequence transduction models are based on complex recurrent or convolutional neural" " networks in an encoder-decoder configuration. The best performing models also connect the" " encoder and decoder through an attention mechanism. We propose a new simple network" " architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence" " and convolutions entirely. Experiments on two machine translation tasks show these models to be" " superior in quality while being more parallelizable and requiring significantly less time to" " train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task," " improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014" " English-to-French translation task, our model establishes a new single-model state-of-the-art" " BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training" " costs of the best models from the literature. We show that the Transformer generalizes well to" " other tasks by applying it successfully to English constituency parsing both with large and" " limited training data." ), "labels": ["translation", "machine learning", "vision", "statistics"], "scores": [0.817, 0.713, 0.018, 0.018], } , )
340
1
from argparse import ArgumentParser from .env import EnvironmentCommand def UpperCamelCase ( ) -> Any: '''simple docstring''' lowercase_ :Any = ArgumentParser('''Diffusers CLI tool''' , usage='''diffusers-cli <command> [<args>]''' ) lowercase_ :List[Any] = parser.add_subparsers(help='''diffusers-cli command helpers''' ) # Register commands EnvironmentCommand.register_subcommand(_a ) # Let's go lowercase_ :Union[str, Any] = parser.parse_args() if not hasattr(_a , '''func''' ): parser.print_help() exit(1 ) # Run lowercase_ :Optional[Any] = args.func(_a ) service.run() if __name__ == "__main__": main()
700
def UpperCamelCase ( _a , _a ) -> int: '''simple docstring''' while a != 0: lowercase_ , lowercase_ :Union[str, Any] = b % a, a return b def UpperCamelCase ( _a , _a ) -> int: '''simple docstring''' if gcd(_a , _a ) != 1: lowercase_ :Union[str, Any] = f"mod inverse of {a!r} and {m!r} does not exist" raise ValueError(_a ) lowercase_ , lowercase_ , lowercase_ :Any = 1, 0, a lowercase_ , lowercase_ , lowercase_ :List[str] = 0, 1, m while va != 0: lowercase_ :Tuple = ua // va lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ :Optional[int] = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va return ua % m
441
0
import requests from bsa import BeautifulSoup def _A ( lowerCamelCase = "https://www.worldometers.info/coronavirus" ): a__ : List[str] = BeautifulSoup(requests.get(lowerCamelCase ).text , "html.parser" ) a__ : List[Any] = soup.findAll("h1" ) a__ : List[str] = soup.findAll("div" , {"class": "maincounter-number"} ) keys += soup.findAll("span" , {"class": "panel-title"} ) values += soup.findAll("div" , {"class": "number-table-main"} ) return {key.text.strip(): value.text.strip() for key, value in zip(lowerCamelCase , lowerCamelCase )} if __name__ == "__main__": print("""\033[1m""" + """COVID-19 Status of the World""" + """\033[0m\n""") for key, value in world_covidaa_stats().items(): print(f'{key}\n{value}\n')
112
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : int = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off SCREAMING_SNAKE_CASE__ : int = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_7, 3_6_6, 4_3_8, 5_3_2, 6_8_5, 7_0_5, 7_9_6, 9_3_0, 1_0_5_8, 1_2_2_0, 1_2_6_7, 1_2_7_9, 1_3_0_3, 1_3_4_3, 1_3_7_7, 1_3_9_1, 1_6_3_5, 1_7_8_2, 1_8_7_5, 2_1_6_2, 2_3_6_1, 2_4_8_8, 3_4_6_7, 4_0_0_8, 4_2_1_1, 4_6_0_0, 4_8_0_8, 5_2_9_9, 5_8_5_5, 6_3_2_9, 7_2_0_3, 9_6_0_9, 9_9_5_9, 1_0_5_6_3, 1_0_7_8_6, 1_1_4_2_0, 1_1_7_0_9, 1_1_9_0_7, 1_3_1_6_3, 1_3_6_9_7, 1_3_7_0_0, 1_4_8_0_8, 1_5_3_0_6, 1_6_4_1_0, 1_6_7_9_1, 1_7_9_9_2, 1_9_2_0_3, 1_9_5_1_0, 2_0_7_2_4, 2_2_3_0_5, 2_2_9_3_5, 2_7_0_0_7, 3_0_1_0_9, 3_0_4_2_0, 3_3_4_0_9, 3_4_9_4_9, 4_0_2_8_3, 4_0_4_9_3, 4_0_5_4_9, 4_7_2_8_2, 4_9_1_4_6, 5_0_2_5_7, 5_0_3_5_9, 5_0_3_6_0, 5_0_3_6_1 ] SCREAMING_SNAKE_CASE__ : List[str] = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_9, 5_0_3, 5_2_2, 5_4_2, 8_7_3, 8_9_3, 9_0_2, 9_1_8, 9_2_2, 9_3_1, 1_3_5_0, 1_8_5_3, 1_9_8_2, 2_4_6_0, 2_6_2_7, 3_2_4_6, 3_2_5_3, 3_2_6_8, 3_5_3_6, 3_8_4_6, 3_9_6_1, 4_1_8_3, 4_6_6_7, 6_5_8_5, 6_6_4_7, 7_2_7_3, 9_0_6_1, 9_3_8_3, 1_0_4_2_8, 1_0_9_2_9, 1_1_9_3_8, 1_2_0_3_3, 1_2_3_3_1, 1_2_5_6_2, 1_3_7_9_3, 1_4_1_5_7, 1_4_6_3_5, 1_5_2_6_5, 1_5_6_1_8, 1_6_5_5_3, 1_6_6_0_4, 1_8_3_6_2, 1_8_9_5_6, 2_0_0_7_5, 2_1_6_7_5, 2_2_5_2_0, 2_6_1_3_0, 2_6_1_6_1, 2_6_4_3_5, 2_8_2_7_9, 2_9_4_6_4, 3_1_6_5_0, 3_2_3_0_2, 3_2_4_7_0, 3_6_8_6_5, 4_2_8_6_3, 4_7_4_2_5, 4_9_8_7_0, 5_0_2_5_4, 5_0_2_5_8, 5_0_3_6_0, 5_0_3_6_1, 5_0_3_6_2 ] class __lowerCAmelCase ( _UpperCamelCase ): _UpperCamelCase : Any = """whisper""" _UpperCamelCase : Union[str, Any] = ["""past_key_values"""] _UpperCamelCase : Union[str, Any] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , snake_case=51_865 , snake_case=80 , snake_case=6 , snake_case=4 , snake_case=6 , snake_case=4 , snake_case=1_536 , snake_case=1_536 , snake_case=0.0 , snake_case=0.0 , snake_case=50_257 , snake_case=True , snake_case=True , snake_case="gelu" , snake_case=256 , snake_case=0.0 , snake_case=0.0 , snake_case=0.0 , snake_case=0.02 , snake_case=False , snake_case=1_500 , snake_case=448 , snake_case=50_256 , snake_case=50_256 , snake_case=50_256 , snake_case=None , snake_case=[220, 50_256] , snake_case=False , snake_case=256 , snake_case=False , snake_case=0.05 , snake_case=10 , snake_case=2 , snake_case=0.0 , snake_case=10 , snake_case=0 , snake_case=7 , **snake_case , ) -> Dict: """simple docstring""" a__ : Optional[Any] = vocab_size a__ : int = num_mel_bins a__ : Dict = d_model a__ : List[Any] = encoder_layers a__ : List[Any] = encoder_attention_heads a__ : Optional[int] = decoder_layers a__ : int = decoder_attention_heads a__ : Optional[Any] = decoder_ffn_dim a__ : List[Any] = encoder_ffn_dim a__ : int = dropout a__ : Optional[int] = attention_dropout a__ : Tuple = activation_dropout a__ : Optional[Any] = activation_function a__ : List[Any] = init_std a__ : List[Any] = encoder_layerdrop a__ : Dict = decoder_layerdrop a__ : List[Any] = use_cache a__ : Union[str, Any] = encoder_layers a__ : Union[str, Any] = scale_embedding # scale factor will be sqrt(d_model) if True a__ : Tuple = max_source_positions a__ : Optional[Any] = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. a__ : Optional[Any] = classifier_proj_size a__ : int = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 a__ : Tuple = apply_spec_augment a__ : int = mask_time_prob a__ : Optional[Any] = mask_time_length a__ : List[str] = mask_time_min_masks a__ : List[str] = mask_feature_prob a__ : Dict = mask_feature_length a__ : Any = mask_feature_min_masks a__ : List[str] = median_filter_width super().__init__( pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , is_encoder_decoder=snake_case , decoder_start_token_id=snake_case , suppress_tokens=snake_case , begin_suppress_tokens=snake_case , **snake_case , ) class __lowerCAmelCase ( _UpperCamelCase ): @property def _snake_case ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" a__ : Dict = OrderedDict( [ ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}), ] ) if self.use_past: a__ : Tuple = {0: "batch"} else: a__ : Union[str, Any] = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(snake_case , direction="inputs" ) return common_inputs def _snake_case ( self , snake_case , snake_case = -1 , snake_case = -1 , snake_case = False , snake_case = None , snake_case = 22_050 , snake_case = 5.0 , snake_case = 220 , ) -> Mapping[str, Any]: """simple docstring""" a__ : int = OrderedDict() a__ : List[str] = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=snake_case , framework=snake_case , sampling_rate=snake_case , time_duration=snake_case , frequency=snake_case , ) a__ : Optional[int] = encoder_inputs["input_features"].shape[2] a__ : str = encoder_sequence_length // 2 if self.use_past else seq_length a__ : Optional[int] = super().generate_dummy_inputs( preprocessor.tokenizer , snake_case , snake_case , snake_case , snake_case ) a__ : Any = encoder_inputs.pop("input_features" ) a__ : Dict = decoder_inputs.pop("decoder_input_ids" ) if "past_key_values" in decoder_inputs: a__ : Tuple = decoder_inputs.pop("past_key_values" ) return dummy_inputs @property def _snake_case ( self ) -> float: """simple docstring""" return 1E-3
112
1
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def __lowercase( UpperCAmelCase__ ): """simple docstring""" if isinstance(UpperCAmelCase__ , collections.abc.Iterable ): return x return (x, x) @require_tf class lowerCamelCase__ : """simple docstring""" def _a (self , __a , __a ): '''simple docstring''' pass def _a (self ): '''simple docstring''' pass def _a (self ): '''simple docstring''' pass def _a (self , __a , __a , __a , __a , __a=None , **__a ): '''simple docstring''' lowerCamelCase = VisionTextDualEncoderConfig.from_vision_text_configs(__a , __a ) lowerCamelCase = TFVisionTextDualEncoderModel(__a ) lowerCamelCase = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], config.projection_dim) ) def _a (self , __a , __a , __a , __a , __a=None , **__a ): '''simple docstring''' lowerCamelCase , lowerCamelCase = self.get_vision_text_model(__a , __a ) lowerCamelCase = TFVisionTextDualEncoderModel(vision_model=__a , text_model=__a ) lowerCamelCase = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def _a (self , __a , __a , __a , __a , __a=None , **__a ): '''simple docstring''' lowerCamelCase , lowerCamelCase = self.get_vision_text_model(__a , __a ) lowerCamelCase = {"vision_model": vision_model, "text_model": text_model} lowerCamelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**__a ) lowerCamelCase = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) self.assertEqual(output["text_embeds"].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output["image_embeds"].shape , (pixel_values.shape[0], model.config.projection_dim) ) def _a (self , __a , __a , __a , __a , __a=None , **__a ): '''simple docstring''' lowerCamelCase , lowerCamelCase = self.get_vision_text_model(__a , __a ) lowerCamelCase = TFVisionTextDualEncoderModel(vision_model=__a , text_model=__a ) lowerCamelCase = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) lowerCamelCase = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__a ) lowerCamelCase = TFVisionTextDualEncoderModel.from_pretrained(__a ) lowerCamelCase = model(input_ids=__a , pixel_values=__a , attention_mask=__a ) lowerCamelCase = after_output[0].numpy() lowerCamelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__a , 1E-5 ) def _a (self , __a , __a , __a , __a , __a=None , **__a ): '''simple docstring''' lowerCamelCase , lowerCamelCase = self.get_vision_text_model(__a , __a ) lowerCamelCase = TFVisionTextDualEncoderModel(vision_model=__a , text_model=__a ) lowerCamelCase = model( input_ids=__a , pixel_values=__a , attention_mask=__a , output_attentions=__a ) lowerCamelCase = output.vision_model_output.attentions self.assertEqual(len(__a ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCamelCase = to_atuple(vision_model.config.image_size ) lowerCamelCase = to_atuple(vision_model.config.patch_size ) lowerCamelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowerCamelCase = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) lowerCamelCase = output.text_model_output.attentions self.assertEqual(len(__a ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def _a (self , __a , __a , __a ): '''simple docstring''' lowerCamelCase = np.abs((a - b) ).max() self.assertLessEqual(__a , __a , F"""Difference between torch and flax is {diff} (>= {tol}).""" ) def _a (self ): '''simple docstring''' lowerCamelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**__a ) def _a (self ): '''simple docstring''' lowerCamelCase = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**__a ) def _a (self ): '''simple docstring''' lowerCamelCase = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**__a ) def _a (self ): '''simple docstring''' lowerCamelCase = self.prepare_config_and_inputs() self.check_save_load(**__a ) def _a (self ): '''simple docstring''' lowerCamelCase = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**__a ) @slow def _a (self ): '''simple docstring''' lowerCamelCase , lowerCamelCase = self.get_pretrained_model_and_inputs() lowerCamelCase = model_a(**__a ) lowerCamelCase = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(__a ) lowerCamelCase = TFVisionTextDualEncoderModel.from_pretrained(__a ) lowerCamelCase = model_a(**__a ) lowerCamelCase = after_outputs[0].numpy() lowerCamelCase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__a , 1E-5 ) @require_tf class lowerCamelCase__ ( UpperCAmelCase_ , unittest.TestCase): """simple docstring""" def _a (self ): '''simple docstring''' lowerCamelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) lowerCamelCase = 13 lowerCamelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowerCamelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowerCamelCase = random_attention_mask([batch_size, 4] ) lowerCamelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def _a (self , __a , __a ): '''simple docstring''' lowerCamelCase = TFViTModel(__a , name="vision_model" ) lowerCamelCase = TFBertModel(__a , name="text_model" ) return vision_model, text_model def _a (self ): '''simple docstring''' lowerCamelCase = TFViTModelTester(self ) lowerCamelCase = TFBertModelTester(self ) lowerCamelCase = vit_model_tester.prepare_config_and_inputs() lowerCamelCase = bert_model_tester.prepare_config_and_inputs() lowerCamelCase , lowerCamelCase , lowerCamelCase = vision_config_and_inputs ( ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class lowerCamelCase__ ( UpperCAmelCase_ , unittest.TestCase): """simple docstring""" def _a (self ): '''simple docstring''' lowerCamelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) lowerCamelCase = 13 lowerCamelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowerCamelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowerCamelCase = random_attention_mask([batch_size, 4] ) lowerCamelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def _a (self , __a , __a , __a , __a , __a=None , **__a ): '''simple docstring''' lowerCamelCase , lowerCamelCase = self.get_vision_text_model(__a , __a ) lowerCamelCase = TFVisionTextDualEncoderModel(vision_model=__a , text_model=__a ) lowerCamelCase = model( input_ids=__a , pixel_values=__a , attention_mask=__a , output_attentions=__a ) lowerCamelCase = output.vision_model_output.attentions self.assertEqual(len(__a ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) lowerCamelCase = to_atuple(vision_model.config.image_size ) lowerCamelCase = to_atuple(vision_model.config.patch_size ) lowerCamelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) lowerCamelCase = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) lowerCamelCase = output.text_model_output.attentions self.assertEqual(len(__a ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def _a (self , __a , __a ): '''simple docstring''' lowerCamelCase = TFDeiTModel(__a , name="vision_model" ) lowerCamelCase = TFRobertaModel(__a , name="text_model" ) return vision_model, text_model def _a (self ): '''simple docstring''' lowerCamelCase = TFDeiTModelTester(self ) lowerCamelCase = TFRobertaModelTester(self ) lowerCamelCase = vit_model_tester.prepare_config_and_inputs() lowerCamelCase = bert_model_tester.prepare_config_and_inputs() lowerCamelCase , lowerCamelCase , lowerCamelCase = vision_config_and_inputs ( ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class lowerCamelCase__ ( UpperCAmelCase_ , unittest.TestCase): """simple docstring""" def _a (self ): '''simple docstring''' lowerCamelCase = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) lowerCamelCase = 13 lowerCamelCase = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) lowerCamelCase = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) lowerCamelCase = random_attention_mask([batch_size, 4] ) lowerCamelCase = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def _a (self , __a , __a ): '''simple docstring''' lowerCamelCase = TFCLIPVisionModel(__a , name="vision_model" ) lowerCamelCase = TFBertModel(__a , name="text_model" ) return vision_model, text_model def _a (self ): '''simple docstring''' lowerCamelCase = TFCLIPVisionModelTester(self ) lowerCamelCase = TFBertModelTester(self ) lowerCamelCase = clip_model_tester.prepare_config_and_inputs() lowerCamelCase = bert_model_tester.prepare_config_and_inputs() lowerCamelCase , lowerCamelCase = vision_config_and_inputs ( ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class lowerCamelCase__ ( unittest.TestCase): """simple docstring""" @slow def _a (self ): '''simple docstring''' lowerCamelCase = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=__a ) lowerCamelCase = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) lowerCamelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) lowerCamelCase = processor( text=["una foto di un gatto", "una foto di un cane"] , images=__a , padding=__a , return_tensors="np" ) lowerCamelCase = model(**__a ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) lowerCamelCase = np.array([[1.228_4727, 0.310_4122]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , __a , atol=1E-3 ) )
484
from __future__ import annotations from collections import deque from collections.abc import Iterator from dataclasses import dataclass @dataclass class lowerCamelCase__ : """simple docstring""" _A = 42 _A = 42 class lowerCamelCase__ : """simple docstring""" def __init__(self , __a ): '''simple docstring''' lowerCamelCase = [[] for _ in range(__a )] lowerCamelCase = size def __getitem__(self , __a ): '''simple docstring''' return iter(self._graph[vertex] ) @property def _a (self ): '''simple docstring''' return self._size def _a (self , __a , __a , __a ): '''simple docstring''' if weight not in (0, 1): raise ValueError("Edge weight must be either 0 or 1." ) if to_vertex < 0 or to_vertex >= self.size: raise ValueError("Vertex indexes must be in [0; size)." ) self._graph[from_vertex].append(Edge(__a , __a ) ) def _a (self , __a , __a ): '''simple docstring''' lowerCamelCase = deque([start_vertex] ) lowerCamelCase = [None] * self.size lowerCamelCase = 0 while queue: lowerCamelCase = queue.popleft() lowerCamelCase = distances[current_vertex] if current_distance is None: continue for edge in self[current_vertex]: lowerCamelCase = current_distance + edge.weight lowerCamelCase = distances[edge.destination_vertex] if ( isinstance(__a , __a ) and new_distance >= dest_vertex_distance ): continue lowerCamelCase = new_distance if edge.weight == 0: queue.appendleft(edge.destination_vertex ) else: queue.append(edge.destination_vertex ) if distances[finish_vertex] is None: raise ValueError("No path from start_vertex to finish_vertex." ) return distances[finish_vertex] if __name__ == "__main__": import doctest doctest.testmod()
484
1
from PIL import Image def lowercase_ ( SCREAMING_SNAKE_CASE : Image ): """simple docstring""" snake_case__, snake_case__ : Tuple =image.size snake_case__ : List[Any] =0 snake_case__ : List[str] =image.load() for i in range(SCREAMING_SNAKE_CASE ): for j in range(SCREAMING_SNAKE_CASE ): snake_case__ : Any =pixels[j, i] mean += pixel mean //= width * height for j in range(SCREAMING_SNAKE_CASE ): for i in range(SCREAMING_SNAKE_CASE ): snake_case__ : int =2_55 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": lowerCamelCase__ = mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
381
def lowercase_ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : str ): """simple docstring""" snake_case__ : int =len(SCREAMING_SNAKE_CASE ) snake_case__ : int =len(SCREAMING_SNAKE_CASE ) snake_case__ : int =( first_str_length if first_str_length > second_str_length else second_str_length ) snake_case__ : list =[] for char_count in range(SCREAMING_SNAKE_CASE ): if char_count < first_str_length: output_list.append(first_str[char_count] ) if char_count < second_str_length: output_list.append(second_str[char_count] ) return "".join(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": print(alternative_string_arrange('''AB''', '''XYZ'''), end=''' ''')
381
1
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys __SCREAMING_SNAKE_CASE : Dict = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') __SCREAMING_SNAKE_CASE : int = subprocess.check_output(F'''git diff --name-only {fork_point_sha}'''.split()).decode('utf-8').split() __SCREAMING_SNAKE_CASE : str = '|'.join(sys.argv[1:]) __SCREAMING_SNAKE_CASE : str = re.compile(RF'''^({joined_dirs}).*?\.py$''') __SCREAMING_SNAKE_CASE : Optional[Any] = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
580
import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerate.test_utils import require_multi_gpu class lowercase_ ( nn.Module ): def __init__( self ): super().__init__() _snake_case : Optional[int] = nn.Linear(3 , 4 ) _snake_case : Any = nn.BatchNormad(4 ) _snake_case : List[str] = nn.Linear(4 , 5 ) def UpperCamelCase ( self , lowercase_ ): return self.lineara(self.batchnorm(self.lineara(lowercase_ ) ) ) class lowercase_ ( __snake_case ): def UpperCamelCase ( self , lowercase_ , *lowercase_ , **lowercase_ ): return (args[0] + 1,) + args[1:], kwargs class lowercase_ ( __snake_case ): def UpperCamelCase ( self , lowercase_ , lowercase_ ): return output + 1 class lowercase_ ( unittest.TestCase ): def UpperCamelCase ( self ): _snake_case : List[str] = ModelForTest() _snake_case : List[str] = ModelHook() add_hook_to_module(lowercase_ , lowercase_ ) self.assertEqual(test_model._hf_hook , lowercase_ ) self.assertTrue(hasattr(lowercase_ , "_old_forward" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , "forward" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["x"] ) remove_hook_from_module(lowercase_ ) self.assertFalse(hasattr(lowercase_ , "_hf_hook" ) ) self.assertFalse(hasattr(lowercase_ , "_old_forward" ) ) def UpperCamelCase ( self ): _snake_case : Optional[Any] = ModelForTest() _snake_case : Any = ModelHook() add_hook_to_module(lowercase_ , lowercase_ ) add_hook_to_module(lowercase_ , lowercase_ , append=lowercase_ ) self.assertEqual(isinstance(test_model._hf_hook , lowercase_ ) , lowercase_ ) self.assertEqual(len(test_model._hf_hook.hooks ) , 2 ) self.assertTrue(hasattr(lowercase_ , "_old_forward" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , "forward" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["x"] ) remove_hook_from_module(lowercase_ ) self.assertFalse(hasattr(lowercase_ , "_hf_hook" ) ) self.assertFalse(hasattr(lowercase_ , "_old_forward" ) ) def UpperCamelCase ( self ): _snake_case : Union[str, Any] = ModelForTest() _snake_case : Tuple = torch.randn(2 , 3 ) _snake_case : List[str] = test_model(x + 1 ) _snake_case : str = test_model(x + 2 ) _snake_case : int = PreForwardHook() add_hook_to_module(lowercase_ , lowercase_ ) _snake_case : Any = test_model(lowercase_ ) self.assertTrue(torch.allclose(lowercase_ , lowercase_ , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain _snake_case : str = PreForwardHook() add_hook_to_module(lowercase_ , lowercase_ ) _snake_case : Union[str, Any] = test_model(lowercase_ ) self.assertTrue(torch.allclose(lowercase_ , lowercase_ , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks _snake_case : Optional[Any] = SequentialHook(PreForwardHook() , PreForwardHook() ) add_hook_to_module(lowercase_ , lowercase_ ) _snake_case : Optional[Any] = test_model(lowercase_ ) assert torch.allclose(lowercase_ , lowercase_ , atol=1e-5 ) def UpperCamelCase ( self ): _snake_case : Optional[Any] = ModelForTest() _snake_case : Dict = torch.randn(2 , 3 ) _snake_case : List[str] = test_model(lowercase_ ) _snake_case : Any = PostForwardHook() add_hook_to_module(lowercase_ , lowercase_ ) _snake_case : Optional[int] = test_model(lowercase_ ) self.assertTrue(torch.allclose(lowercase_ , output + 1 , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain _snake_case : Tuple = PostForwardHook() add_hook_to_module(lowercase_ , lowercase_ ) _snake_case : Any = test_model(lowercase_ ) self.assertTrue(torch.allclose(lowercase_ , output + 1 , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks _snake_case : Union[str, Any] = SequentialHook(PostForwardHook() , PostForwardHook() ) add_hook_to_module(lowercase_ , lowercase_ ) _snake_case : Any = test_model(lowercase_ ) assert torch.allclose(lowercase_ , output + 2 , atol=1e-5 ) def UpperCamelCase ( self ): _snake_case : Dict = ModelForTest() _snake_case : List[str] = torch.randn(2 , 3 ) _snake_case : int = test_model(lowercase_ ) _snake_case : str = PostForwardHook() add_hook_to_module(lowercase_ , lowercase_ ) _snake_case : Dict = test_model(lowercase_ ) self.assertTrue(torch.allclose(lowercase_ , output + 1 ) ) self.assertTrue(outputa.requires_grad ) _snake_case : Dict = True _snake_case : str = test_model(lowercase_ ) self.assertFalse(outputa.requires_grad ) @require_multi_gpu def UpperCamelCase ( self ): _snake_case : List[Any] = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) # This will move each submodule on different devices add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=1 ) ) self.assertEqual(model.lineara.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device(0 ) ) self.assertEqual(model.lineara.weight.device , torch.device(1 ) ) # We can still make a forward pass. The input does not need to be on any particular device _snake_case : str = torch.randn(2 , 3 ) _snake_case : int = model(lowercase_ ) self.assertEqual(output.device , torch.device(1 ) ) # We can add a general hook to put back output on same device as input. add_hook_to_module(lowercase_ , AlignDevicesHook(io_same_device=lowercase_ ) ) _snake_case : str = torch.randn(2 , 3 ).to(0 ) _snake_case : Dict = model(lowercase_ ) self.assertEqual(output.device , torch.device(0 ) ) def UpperCamelCase ( self ): _snake_case : Any = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) # This will move each submodule on different devices _snake_case : Tuple = {"execution_device": 0 if torch.cuda.is_available() else "cpu", "offload": True} add_hook_to_module(model.lineara , AlignDevicesHook(**lowercase_ ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**lowercase_ ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**lowercase_ ) ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("meta" ) ) self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) # Buffers are not included in the offload by default, so are on the execution device _snake_case : Optional[Any] = torch.device(hook_kwargs["execution_device"] ) self.assertEqual(model.batchnorm.running_mean.device , lowercase_ ) _snake_case : List[str] = torch.randn(2 , 3 ) _snake_case : Any = model(lowercase_ ) self.assertEqual(output.device , lowercase_ ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) # Now test with buffers included in the offload _snake_case : Dict = { "execution_device": 0 if torch.cuda.is_available() else "cpu", "offload": True, "offload_buffers": True, } add_hook_to_module(model.lineara , AlignDevicesHook(**lowercase_ ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**lowercase_ ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**lowercase_ ) ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("meta" ) ) self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("meta" ) ) _snake_case : List[str] = torch.randn(2 , 3 ) _snake_case : List[str] = model(lowercase_ ) self.assertEqual(output.device , lowercase_ ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) def UpperCamelCase ( self ): _snake_case : Tuple = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) # This will move each submodule on different devices _snake_case : Any = 0 if torch.cuda.is_available() else "cpu" attach_align_device_hook(lowercase_ , execution_device=lowercase_ , offload=lowercase_ ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("meta" ) ) self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) # Buffers are not included in the offload by default, so are on the execution device _snake_case : Optional[int] = torch.device(lowercase_ ) self.assertEqual(model.batchnorm.running_mean.device , lowercase_ ) _snake_case : Dict = torch.randn(2 , 3 ) _snake_case : int = model(lowercase_ ) self.assertEqual(output.device , lowercase_ ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(lowercase_ ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) # Now test with buffers included in the offload attach_align_device_hook(lowercase_ , execution_device=lowercase_ , offload=lowercase_ , offload_buffers=lowercase_ ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("meta" ) ) self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("meta" ) ) _snake_case : int = torch.randn(2 , 3 ) _snake_case : str = model(lowercase_ ) self.assertEqual(output.device , lowercase_ ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(lowercase_ ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) def UpperCamelCase ( self ): _snake_case : Optional[int] = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) # This will move each submodule on different devices _snake_case : int = 0 if torch.cuda.is_available() else "cpu" attach_align_device_hook( lowercase_ , execution_device=lowercase_ , offload=lowercase_ , weights_map=model.state_dict() ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("meta" ) ) self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) # Buffers are not included in the offload by default, so are on the execution device _snake_case : int = torch.device(lowercase_ ) self.assertEqual(model.batchnorm.running_mean.device , lowercase_ ) _snake_case : Union[str, Any] = torch.randn(2 , 3 ) _snake_case : Dict = model(lowercase_ ) self.assertEqual(output.device , lowercase_ ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(lowercase_ ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) # Now test with buffers included in the offload attach_align_device_hook( lowercase_ , execution_device=lowercase_ , offload=lowercase_ , weights_map=model.state_dict() , offload_buffers=lowercase_ , ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("meta" ) ) self.assertEqual(model.lineara.weight.device , torch.device("meta" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("meta" ) ) _snake_case : List[Any] = torch.randn(2 , 3 ) _snake_case : List[Any] = model(lowercase_ ) self.assertEqual(output.device , lowercase_ ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(lowercase_ ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("cpu" ) ) self.assertEqual(model.lineara.weight.device , torch.device("cpu" ) )
580
1
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig from transformers.testing_utils import ( require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __UpperCAmelCase : """simple docstring""" def __init__( self , __A , __A=13 , __A=3 , __A=True , __A=True , __A=0.1 , __A=0.1 , __A=224 , __A=1000 , __A=[3, 3, 6, 4] , __A=[48, 56, 112, 220] , ): __a = parent __a = batch_size __a = num_channels __a = is_training __a = use_labels __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = num_labels __a = image_size __a = layer_depths __a = embed_dims def snake_case_ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels def snake_case_ ( self ): return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act="""gelu""" , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=__A , layer_scale_init_value=1E-5 , ) def snake_case_ ( self , __A , __A , __A ): __a = SwiftFormerModel(config=__A ) model.to(__A ) model.eval() __a = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def snake_case_ ( self , __A , __A , __A ): __a = self.num_labels __a = SwiftFormerForImageClassification(__A ) model.to(__A ) model.eval() __a = model(__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) __a = SwiftFormerForImageClassification(__A ) model.to(__A ) model.eval() __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case_ ( self ): ((__a) , (__a) , (__a)) = self.prepare_config_and_inputs() __a = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase ( __A , __A , unittest.TestCase ): """simple docstring""" _lowerCamelCase = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () _lowerCamelCase = ( {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification} if is_torch_available() else {} ) _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False def snake_case_ ( self ): __a = SwiftFormerModelTester(self ) __a = ConfigTester( self , config_class=__A , has_text_modality=__A , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def snake_case_ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""SwiftFormer does not use inputs_embeds""" ) def snake_case_ ( self ): pass def snake_case_ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__A ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__A , nn.Linear ) ) def snake_case_ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(__A ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def snake_case_ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def snake_case_ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) @slow def snake_case_ ( self ): for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = SwiftFormerModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @unittest.skip(reason="""SwiftFormer does not output attentions""" ) def snake_case_ ( self ): pass def snake_case_ ( self ): def check_hidden_states_output(__A , __A , __A ): __a = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(__A , __A ) ) __a = outputs.hidden_states __a = 8 self.assertEqual(len(__A ) , __A ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(__A ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(__A , __A , __A ) def snake_case_ ( self ): def _config_zero_init(__A ): __a = copy.deepcopy(__A ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(__A , __A , 1E-10 ) if isinstance(getattr(__A , __A , __A ) , __A ): __a = _config_zero_init(getattr(__A , __A ) ) setattr(__A , __A , __A ) return configs_no_init __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = _config_zero_init(__A ) for model_class in self.all_model_classes: __a = model_class(config=__A ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().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 snake_case_ ( self ): pass def a (): __a = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __UpperCAmelCase ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case_ ( self ): return ViTImageProcessor.from_pretrained("""MBZUAI/swiftformer-xs""" ) if is_vision_available() else None @slow def snake_case_ ( self ): __a = SwiftFormerForImageClassification.from_pretrained("""MBZUAI/swiftformer-xs""" ).to(__A ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=__A , return_tensors="""pt""" ).to(__A ) # forward pass with torch.no_grad(): __a = model(**__A ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __A ) __a = torch.tensor([[-2.1703E00, 2.1107E00, -2.0811E00]] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __A , atol=1E-4 ) )
99
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class a__( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase_ : str = ['''image_processor''', '''tokenizer'''] UpperCAmelCase_ : str = '''ViltImageProcessor''' UpperCAmelCase_ : Any = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self , __lowerCAmelCase=None , __lowerCAmelCase=None , **__lowerCAmelCase): """simple docstring""" lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __lowerCAmelCase , ) lowerCAmelCase = kwargs.pop("""feature_extractor""") lowerCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""") if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""") super().__init__(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = self.image_processor def __call__( self , __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = True , __lowerCAmelCase = False , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = 0 , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = False , __lowerCAmelCase = False , __lowerCAmelCase = False , __lowerCAmelCase = False , __lowerCAmelCase = True , __lowerCAmelCase = None , **__lowerCAmelCase , ): """simple docstring""" lowerCAmelCase = self.tokenizer( text=__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , padding=__lowerCAmelCase , truncation=__lowerCAmelCase , max_length=__lowerCAmelCase , stride=__lowerCAmelCase , pad_to_multiple_of=__lowerCAmelCase , return_token_type_ids=__lowerCAmelCase , return_attention_mask=__lowerCAmelCase , return_overflowing_tokens=__lowerCAmelCase , return_special_tokens_mask=__lowerCAmelCase , return_offsets_mapping=__lowerCAmelCase , return_length=__lowerCAmelCase , verbose=__lowerCAmelCase , return_tensors=__lowerCAmelCase , **__lowerCAmelCase , ) # add pixel_values + pixel_mask lowerCAmelCase = self.image_processor(__lowerCAmelCase , return_tensors=__lowerCAmelCase) encoding.update(__lowerCAmelCase) return encoding def a_ ( self , *__lowerCAmelCase , **__lowerCAmelCase): """simple docstring""" return self.tokenizer.batch_decode(*__lowerCAmelCase , **__lowerCAmelCase) def a_ ( self , *__lowerCAmelCase , **__lowerCAmelCase): """simple docstring""" return self.tokenizer.decode(*__lowerCAmelCase , **__lowerCAmelCase) @property def a_ ( self): """simple docstring""" lowerCAmelCase = self.tokenizer.model_input_names lowerCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names)) @property def a_ ( self): """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __lowerCAmelCase , ) return self.image_processor_class @property def a_ ( self): """simple docstring""" warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __lowerCAmelCase , ) return self.image_processor
370
0
"""simple docstring""" import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_ ): if "model" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('model.', '' ) if "norm1" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('norm1', 'attention.output.LayerNorm' ) if "norm2" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('norm2', 'output.LayerNorm' ) if "norm" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('norm', 'LayerNorm' ) if "transformer" in orig_key: SCREAMING_SNAKE_CASE = orig_key.split('.' )[0].split('_' )[-1] SCREAMING_SNAKE_CASE = orig_key.replace(f'''transformer_{layer_num}''', f'''encoder.layer.{layer_num}''' ) if "mha.attn" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('mha.attn', 'attention.self' ) if "mha" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('mha', 'attention' ) if "W_q" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('W_q', 'self.query' ) if "W_k" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('W_k', 'self.key' ) if "W_v" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('W_v', 'self.value' ) if "ff1" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('ff1', 'intermediate.dense' ) if "ff2" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('ff2', 'output.dense' ) if "ff" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('ff', 'output.dense' ) if "mlm_class" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('mlm.mlm_class', 'cls.predictions.decoder' ) if "mlm" in orig_key: SCREAMING_SNAKE_CASE = orig_key.replace('mlm', 'cls.predictions.transform' ) if "cls" not in orig_key: SCREAMING_SNAKE_CASE = 'yoso.' + orig_key return orig_key def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if ("pooler" in key) or ("sen_class" in key): continue else: SCREAMING_SNAKE_CASE = val SCREAMING_SNAKE_CASE = orig_state_dict['cls.predictions.decoder.bias'] SCREAMING_SNAKE_CASE = torch.arange(SCREAMING_SNAKE_CASE_ ).expand((1, -1) ) + 2 return orig_state_dict def UpperCamelCase_ ( SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): SCREAMING_SNAKE_CASE = torch.load(SCREAMING_SNAKE_CASE_, map_location='cpu' )['model_state_dict'] SCREAMING_SNAKE_CASE = YosoConfig.from_json_file(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = YosoForMaskedLM(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = convert_checkpoint_helper(config.max_position_embeddings, SCREAMING_SNAKE_CASE_ ) print(model.load_state_dict(SCREAMING_SNAKE_CASE_ ) ) model.eval() model.save_pretrained(SCREAMING_SNAKE_CASE_ ) print(f'''Checkpoint successfuly converted. Model saved at {pytorch_dump_path}''' ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( '--pytorch_model_path', default=None, type=str, required=True, help='Path to YOSO pytorch checkpoint.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help='The json file for YOSO model config.', ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) snake_case = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
705
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPSegProcessor, ViTImageProcessor @require_vision class UpperCamelCase ( unittest.TestCase ): """simple docstring""" def A ( self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE = ['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 SCREAMING_SNAKE_CASE = dict(zip(lowercase__ , range(len(lowercase__ ) ) ) ) SCREAMING_SNAKE_CASE = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] SCREAMING_SNAKE_CASE = {'unk_token': '<unk>'} SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(lowercase__ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(lowercase__ ) ) SCREAMING_SNAKE_CASE = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.48_145_466, 0.4_578_275, 0.40_821_073], 'image_std': [0.26_862_954, 0.26_130_258, 0.27_577_711], } SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , lowercase__ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(lowercase__ , lowercase__ ) def A ( self , **lowercase__ ) -> Optional[int]: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowercase__ ) def A ( self , **lowercase__ ) -> Dict: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowercase__ ) def A ( self , **lowercase__ ) -> Union[str, Any]: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **lowercase__ ) def A ( self ) -> Optional[int]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def A ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(lowercase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def A ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=lowercase__ , image_processor=lowercase__ ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase__ ) SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=lowercase__ , image_processor=lowercase__ ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowercase__ ) self.assertIsInstance(processor_fast.tokenizer , lowercase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowercase__ ) self.assertIsInstance(processor_fast.image_processor , lowercase__ ) def A ( self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=lowercase__ , padding_value=1.0 ) SCREAMING_SNAKE_CASE = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=lowercase__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowercase__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowercase__ ) def A ( self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=lowercase__ , image_processor=lowercase__ ) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = image_processor(lowercase__ , return_tensors='np' ) SCREAMING_SNAKE_CASE = processor(images=lowercase__ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def A ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=lowercase__ , image_processor=lowercase__ ) SCREAMING_SNAKE_CASE = 'lower newer' SCREAMING_SNAKE_CASE = processor(text=lowercase__ ) SCREAMING_SNAKE_CASE = tokenizer(lowercase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def A ( self ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=lowercase__ , image_processor=lowercase__ ) SCREAMING_SNAKE_CASE = 'lower newer' SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(text=lowercase__ , images=lowercase__ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(lowercase__ ): processor() def A ( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=lowercase__ , image_processor=lowercase__ ) SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = self.prepare_image_inputs() SCREAMING_SNAKE_CASE = processor(images=lowercase__ , visual_prompt=lowercase__ ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'conditional_pixel_values'] ) # test if it raises when no input is passed with pytest.raises(lowercase__ ): processor() def A ( self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = self.get_image_processor() SCREAMING_SNAKE_CASE = self.get_tokenizer() SCREAMING_SNAKE_CASE = CLIPSegProcessor(tokenizer=lowercase__ , image_processor=lowercase__ ) SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE = processor.batch_decode(lowercase__ ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(lowercase__ ) self.assertListEqual(lowercase__ , lowercase__ )
406
0
import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder __a: Dict = logging.get_logger(__name__) # pylint: disable=invalid-name __a: Dict = 256 class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ): '''simple docstring''' _lowerCamelCase = ['''melgan'''] def __init__( self : List[str] , lowerCamelCase : SpectrogramNotesEncoder , lowerCamelCase : SpectrogramContEncoder , lowerCamelCase : TaFilmDecoder , lowerCamelCase : DDPMScheduler , lowerCamelCase : OnnxRuntimeModel if is_onnx_available() else Any , ) -> None: """simple docstring""" super().__init__() # From MELGAN _UpperCAmelCase = math.log(1E-5 ) # Matches MelGAN training. _UpperCAmelCase = 4.0 # Largest value for most examples _UpperCAmelCase = 128 self.register_modules( notes_encoder=lowerCamelCase , continuous_encoder=lowerCamelCase , decoder=lowerCamelCase , scheduler=lowerCamelCase , melgan=lowerCamelCase , ) def lowerCamelCase ( self : List[str] , lowerCamelCase : List[str] , lowerCamelCase : int=(-1.0, 1.0) , lowerCamelCase : List[str]=False ) -> List[Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = output_range if clip: _UpperCAmelCase = torch.clip(lowerCamelCase , self.min_value , self.max_value ) # Scale to [0, 1]. _UpperCAmelCase = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def lowerCamelCase ( self : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : Any=(-1.0, 1.0) , lowerCamelCase : Tuple=False ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = input_range _UpperCAmelCase = torch.clip(lowerCamelCase , lowerCamelCase , lowerCamelCase ) if clip else outputs # Scale to [0, 1]. _UpperCAmelCase = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def lowerCamelCase ( self : List[str] , lowerCamelCase : Optional[int] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[Any] ) -> Any: """simple docstring""" _UpperCAmelCase = input_tokens > 0 _UpperCAmelCase , _UpperCAmelCase = self.notes_encoder( encoder_input_tokens=lowerCamelCase , encoder_inputs_mask=lowerCamelCase ) _UpperCAmelCase , _UpperCAmelCase = self.continuous_encoder( encoder_inputs=lowerCamelCase , encoder_inputs_mask=lowerCamelCase ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def lowerCamelCase ( self : List[Any] , lowerCamelCase : str , lowerCamelCase : int , lowerCamelCase : Tuple ) -> str: """simple docstring""" _UpperCAmelCase = noise_time if not torch.is_tensor(lowerCamelCase ): _UpperCAmelCase = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(lowerCamelCase ) and len(timesteps.shape ) == 0: _UpperCAmelCase = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML _UpperCAmelCase = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) _UpperCAmelCase = self.decoder( encodings_and_masks=lowerCamelCase , decoder_input_tokens=lowerCamelCase , decoder_noise_time=lowerCamelCase ) return logits @torch.no_grad() def __call__( self : Optional[int] , lowerCamelCase : List[List[int]] , lowerCamelCase : Optional[torch.Generator] = None , lowerCamelCase : int = 100 , lowerCamelCase : bool = True , lowerCamelCase : str = "numpy" , lowerCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase : int = 1 , ) -> Union[AudioPipelineOutput, Tuple]: """simple docstring""" if (callback_steps is None) or ( callback_steps is not None and (not isinstance(lowerCamelCase , lowerCamelCase ) or callback_steps <= 0) ): raise ValueError( f"""`callback_steps` has to be a positive integer but is {callback_steps} of type""" f""" {type(lowerCamelCase )}.""" ) _UpperCAmelCase = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) _UpperCAmelCase = np.zeros([1, 0, self.n_dims] , np.floataa ) _UpperCAmelCase = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=lowerCamelCase , device=self.device ) for i, encoder_input_tokens in enumerate(lowerCamelCase ): if i == 0: _UpperCAmelCase = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. _UpperCAmelCase = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=lowerCamelCase , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. _UpperCAmelCase = ones _UpperCAmelCase = self.scale_features( lowerCamelCase , output_range=[-1.0, 1.0] , clip=lowerCamelCase ) _UpperCAmelCase = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=lowerCamelCase , continuous_mask=lowerCamelCase , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop _UpperCAmelCase = randn_tensor( shape=encoder_continuous_inputs.shape , generator=lowerCamelCase , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(lowerCamelCase ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): _UpperCAmelCase = self.decode( encodings_and_masks=lowerCamelCase , input_tokens=lowerCamelCase , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 _UpperCAmelCase = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , generator=lowerCamelCase ).prev_sample _UpperCAmelCase = self.scale_to_features(lowerCamelCase , input_range=[-1.0, 1.0] ) _UpperCAmelCase = mel[:1] _UpperCAmelCase = mel.cpu().float().numpy() _UpperCAmelCase = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(lowerCamelCase , lowerCamelCase ) logger.info("""Generated segment""" , lowerCamelCase ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( """Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'.""" ) elif output_type == "numpy" and self.melgan is None: raise ValueError( """Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'.""" ) if output_type == "numpy": _UpperCAmelCase = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: _UpperCAmelCase = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=lowerCamelCase )
108
import os import zipfile import pytest from datasets.utils.extract import ( BzipaExtractor, Extractor, GzipExtractor, LzaExtractor, SevenZipExtractor, TarExtractor, XzExtractor, ZipExtractor, ZstdExtractor, ) from .utils import require_lza, require_pyazr, require_zstandard @pytest.mark.parametrize( '''compression_format, is_archive''' , [ ('''7z''', True), ('''bz2''', False), ('''gzip''', False), ('''lz4''', False), ('''tar''', True), ('''xz''', False), ('''zip''', True), ('''zstd''', False), ] , ) def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a , __a , __a , __a , __a , __a , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str ={ '''7z''': (seven_zip_file, SevenZipExtractor), '''bz2''': (bza_file, BzipaExtractor), '''gzip''': (gz_file, GzipExtractor), '''lz4''': (lza_file, LzaExtractor), '''tar''': (tar_file, TarExtractor), '''xz''': (xz_file, XzExtractor), '''zip''': (zip_file, ZipExtractor), '''zstd''': (zstd_file, ZstdExtractor), } SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] =input_paths_and_base_extractors[compression_format] if input_path is None: SCREAMING_SNAKE_CASE : Union[str, Any] =f'for \'{compression_format}\' compression_format, ' if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(__a ) assert base_extractor.is_extractable(__a ) SCREAMING_SNAKE_CASE : Tuple =tmp_path / ('''extracted''' if is_archive else '''extracted.txt''') base_extractor.extract(__a , __a ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name SCREAMING_SNAKE_CASE : List[str] =file_path.read_text(encoding='''utf-8''' ) else: SCREAMING_SNAKE_CASE : Dict =output_path.read_text(encoding='''utf-8''' ) SCREAMING_SNAKE_CASE : Optional[int] =text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.mark.parametrize( '''compression_format, is_archive''' , [ ('''7z''', True), ('''bz2''', False), ('''gzip''', False), ('''lz4''', False), ('''tar''', True), ('''xz''', False), ('''zip''', True), ('''zstd''', False), ] , ) def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a , __a , __a , __a , __a , __a , __a , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] ={ '''7z''': seven_zip_file, '''bz2''': bza_file, '''gzip''': gz_file, '''lz4''': lza_file, '''tar''': tar_file, '''xz''': xz_file, '''zip''': zip_file, '''zstd''': zstd_file, } SCREAMING_SNAKE_CASE : Any =input_paths[compression_format] if input_path is None: SCREAMING_SNAKE_CASE : int =f'for \'{compression_format}\' compression_format, ' if compression_format == "7z": reason += require_pyazr.kwargs["reason"] elif compression_format == "lz4": reason += require_lza.kwargs["reason"] elif compression_format == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(__a ) SCREAMING_SNAKE_CASE : int =Extractor.infer_extractor_format(__a ) assert extractor_format is not None SCREAMING_SNAKE_CASE : List[str] =tmp_path / ('''extracted''' if is_archive else '''extracted.txt''') Extractor.extract(__a , __a , __a ) if is_archive: assert output_path.is_dir() for file_path in output_path.iterdir(): assert file_path.name == text_file.name SCREAMING_SNAKE_CASE : Any =file_path.read_text(encoding='''utf-8''' ) else: SCREAMING_SNAKE_CASE : List[str] =output_path.read_text(encoding='''utf-8''' ) SCREAMING_SNAKE_CASE : List[str] =text_file.read_text(encoding='''utf-8''' ) assert extracted_file_content == expected_file_content @pytest.fixture def lowerCAmelCase_ ( __a , __a ) -> Tuple: """simple docstring""" import tarfile SCREAMING_SNAKE_CASE : Any =tmp_path / '''data_dot_dot''' directory.mkdir() SCREAMING_SNAKE_CASE : Tuple =directory / '''tar_file_with_dot_dot.tar''' with tarfile.TarFile(__a , '''w''' ) as f: f.add(__a , arcname=os.path.join('''..''' , text_file.name ) ) return path @pytest.fixture def lowerCAmelCase_ ( __a ) -> List[str]: """simple docstring""" import tarfile SCREAMING_SNAKE_CASE : List[str] =tmp_path / '''data_sym_link''' directory.mkdir() SCREAMING_SNAKE_CASE : Tuple =directory / '''tar_file_with_sym_link.tar''' os.symlink('''..''' , directory / '''subdir''' , target_is_directory=__a ) with tarfile.TarFile(__a , '''w''' ) as f: f.add(str(directory / '''subdir''' ) , arcname='''subdir''' ) # str required by os.readlink on Windows and Python < 3.8 return path @pytest.mark.parametrize( '''insecure_tar_file, error_log''' , [('''tar_file_with_dot_dot''', '''illegal path'''), ('''tar_file_with_sym_link''', '''Symlink''')] , ) def lowerCAmelCase_ ( __a , __a , __a , __a , __a , __a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : int ={ '''tar_file_with_dot_dot''': tar_file_with_dot_dot, '''tar_file_with_sym_link''': tar_file_with_sym_link, } SCREAMING_SNAKE_CASE : Any =insecure_tar_files[insecure_tar_file] SCREAMING_SNAKE_CASE : Optional[Any] =tmp_path / '''extracted''' TarExtractor.extract(__a , __a ) assert caplog.text for record in caplog.records: assert record.levelname == "ERROR" assert error_log in record.msg def lowerCAmelCase_ ( __a ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] =tmpdir / '''not_a_zip_file''' # From: https://github.com/python/cpython/pull/5053 SCREAMING_SNAKE_CASE : List[Any] =( b'''\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00''' b'''\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6\'\x00\x00\x00\x15I''' b'''DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07''' b'''\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82''' ) with not_a_zip_file.open('''wb''' ) as f: f.write(__a ) assert zipfile.is_zipfile(str(__a ) ) # is a false positive for `zipfile` assert not ZipExtractor.is_extractable(__a ) # but we're right
258
0
'''simple docstring''' def _a ( a : int = 100_0000 ): _SCREAMING_SNAKE_CASE = set(range(3 , _SCREAMING_SNAKE_CASE , 2 ) ) primes.add(2 ) for p in range(3 , _SCREAMING_SNAKE_CASE , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) ) _SCREAMING_SNAKE_CASE = [float(_SCREAMING_SNAKE_CASE ) for n in range(limit + 1 )] for p in primes: for n in range(_SCREAMING_SNAKE_CASE , limit + 1 , _SCREAMING_SNAKE_CASE ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
716
'''simple docstring''' import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class lowerCAmelCase : def lowercase ( self ): torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5" ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5" ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = UNetaDConditionModel( sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[ "ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D", ] , mid_block_type="UNetMidBlock2DSimpleCrossAttn" , up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="text" , addition_embed_type_num_heads=2 , cross_attention_norm="group_norm" , resnet_time_scale_shift="scale_shift" , act_fn="gelu" , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule="squaredcos_cap_v2" , beta_start=0.00_01 , beta_end=0.02 , thresholding=UpperCamelCase , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="epsilon" , variance_type="learned_range" , ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowercase ( self ): torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = TaEncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5" ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5" ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = UNetaDConditionModel( sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[ "ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D", ] , mid_block_type="UNetMidBlock2DSimpleCrossAttn" , up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type="text" , addition_embed_type_num_heads=2 , cross_attention_norm="group_norm" , resnet_time_scale_shift="scale_shift" , act_fn="gelu" , class_embed_type="timestep" , mid_block_scale_factor=1.4_14 , time_embedding_act_fn="gelu" , time_embedding_dim=32 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule="squaredcos_cap_v2" , beta_start=0.00_01 , beta_end=0.02 , thresholding=UpperCamelCase , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="epsilon" , variance_type="learned_range" , ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule="squaredcos_cap_v2" , beta_start=0.00_01 , beta_end=0.02 , ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def lowercase ( self ): _SCREAMING_SNAKE_CASE = self.get_dummy_components() _SCREAMING_SNAKE_CASE = self.pipeline_class(**UpperCamelCase ) pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCamelCase ) _SCREAMING_SNAKE_CASE = inputs["prompt"] _SCREAMING_SNAKE_CASE = inputs["generator"] _SCREAMING_SNAKE_CASE = inputs["num_inference_steps"] _SCREAMING_SNAKE_CASE = inputs["output_type"] if "image" in inputs: _SCREAMING_SNAKE_CASE = inputs["image"] else: _SCREAMING_SNAKE_CASE = None if "mask_image" in inputs: _SCREAMING_SNAKE_CASE = inputs["mask_image"] else: _SCREAMING_SNAKE_CASE = None if "original_image" in inputs: _SCREAMING_SNAKE_CASE = inputs["original_image"] else: _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = pipe.encode_prompt(UpperCamelCase ) # inputs with prompt converted to embeddings _SCREAMING_SNAKE_CASE = { "prompt_embeds": prompt_embeds, "negative_prompt_embeds": negative_prompt_embeds, "generator": generator, "num_inference_steps": num_inference_steps, "output_type": output_type, } if image is not None: _SCREAMING_SNAKE_CASE = image if mask_image is not None: _SCREAMING_SNAKE_CASE = mask_image if original_image is not None: _SCREAMING_SNAKE_CASE = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) _SCREAMING_SNAKE_CASE = pipe(**UpperCamelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(UpperCamelCase ) _SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(UpperCamelCase ) pipe_loaded.to(UpperCamelCase ) pipe_loaded.set_progress_bar_config(disable=UpperCamelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(UpperCamelCase , UpperCamelCase ) is None , F'`{optional_component}` did not stay set to None after loading.' , ) _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCamelCase ) _SCREAMING_SNAKE_CASE = inputs["generator"] _SCREAMING_SNAKE_CASE = inputs["num_inference_steps"] _SCREAMING_SNAKE_CASE = inputs["output_type"] # inputs with prompt converted to embeddings _SCREAMING_SNAKE_CASE = { "prompt_embeds": prompt_embeds, "negative_prompt_embeds": negative_prompt_embeds, "generator": generator, "num_inference_steps": num_inference_steps, "output_type": output_type, } if image is not None: _SCREAMING_SNAKE_CASE = image if mask_image is not None: _SCREAMING_SNAKE_CASE = mask_image if original_image is not None: _SCREAMING_SNAKE_CASE = original_image _SCREAMING_SNAKE_CASE = pipe_loaded(**UpperCamelCase )[0] _SCREAMING_SNAKE_CASE = np.abs(to_np(UpperCamelCase ) - to_np(UpperCamelCase ) ).max() self.assertLess(UpperCamelCase , 1e-4 ) def lowercase ( self ): _SCREAMING_SNAKE_CASE = self.get_dummy_components() _SCREAMING_SNAKE_CASE = self.pipeline_class(**UpperCamelCase ) pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCamelCase ) _SCREAMING_SNAKE_CASE = pipe(**UpperCamelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(UpperCamelCase ) _SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(UpperCamelCase ) pipe_loaded.to(UpperCamelCase ) pipe_loaded.set_progress_bar_config(disable=UpperCamelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCamelCase ) _SCREAMING_SNAKE_CASE = pipe_loaded(**UpperCamelCase )[0] _SCREAMING_SNAKE_CASE = np.abs(to_np(UpperCamelCase ) - to_np(UpperCamelCase ) ).max() self.assertLess(UpperCamelCase , 1e-4 )
493
0
'''simple docstring''' from collections.abc import Callable def __UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ): lowercase__ : float = a lowercase__ : float = b if function(UpperCAmelCase ) == 0: # one of the a or b is a root for the function return a elif function(UpperCAmelCase ) == 0: return b elif ( function(UpperCAmelCase ) * function(UpperCAmelCase ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError('''could not find root in given interval.''' ) else: lowercase__ : float = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(UpperCAmelCase ) == 0: return mid elif function(UpperCAmelCase ) * function(UpperCAmelCase ) < 0: lowercase__ : Any = mid else: lowercase__ : Optional[Any] = mid lowercase__ : Tuple = start + (end - start) / 2.0 return mid def __UpperCamelCase ( UpperCAmelCase ): return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 10_00)) import doctest doctest.testmod()
152
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a: Optional[Any] = { """configuration_bigbird_pegasus""": [ """BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BigBirdPegasusConfig""", """BigBirdPegasusOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a: Dict = [ """BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST""", """BigBirdPegasusForCausalLM""", """BigBirdPegasusForConditionalGeneration""", """BigBirdPegasusForQuestionAnswering""", """BigBirdPegasusForSequenceClassification""", """BigBirdPegasusModel""", """BigBirdPegasusPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __a: int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
152
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: UpperCamelCase = None UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} UpperCamelCase = { '''vocab_file''': { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''', }, '''tokenizer_file''': { '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json''', '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json''', '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json''', '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json''', '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json''', '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json''', '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json''', '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json''', }, } UpperCamelCase = { '''albert-base-v1''': 5_1_2, '''albert-large-v1''': 5_1_2, '''albert-xlarge-v1''': 5_1_2, '''albert-xxlarge-v1''': 5_1_2, '''albert-base-v2''': 5_1_2, '''albert-large-v2''': 5_1_2, '''albert-xlarge-v2''': 5_1_2, '''albert-xxlarge-v2''': 5_1_2, } UpperCamelCase = '''▁''' class lowerCamelCase__ ( _a ): lowerCamelCase_ : Optional[int] = VOCAB_FILES_NAMES lowerCamelCase_ : Any = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ : List[Any] = AlbertTokenizer def __init__(self : Union[str, Any] , _snake_case : Optional[int]=None , _snake_case : Union[str, Any]=None , _snake_case : List[str]=True , _snake_case : Optional[int]=True , _snake_case : int=False , _snake_case : List[str]="[CLS]" , _snake_case : str="[SEP]" , _snake_case : List[str]="<unk>" , _snake_case : Any="[SEP]" , _snake_case : Tuple="<pad>" , _snake_case : Optional[int]="[CLS]" , _snake_case : Tuple="[MASK]" , **_snake_case : List[str] , ) -> Optional[int]: """simple docstring""" lowerCamelCase_ : Dict = ( AddedToken(_A , lstrip=_A , rstrip=_A , normalized=_A ) if isinstance(_A , _A ) else mask_token ) super().__init__( _A , tokenizer_file=_A , do_lower_case=_A , remove_space=_A , keep_accents=_A , bos_token=_A , eos_token=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , **_A , ) lowerCamelCase_ : List[str] = do_lower_case lowerCamelCase_ : Optional[int] = remove_space lowerCamelCase_ : List[str] = keep_accents lowerCamelCase_ : Union[str, Any] = vocab_file lowerCamelCase_ : Dict = False if not self.vocab_file else True def UpperCAmelCase_ (self : Optional[int] , _snake_case : Optional[Any] , _snake_case : Any = None ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ : Union[str, Any] = [self.sep_token_id] lowerCamelCase_ : Dict = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase_ (self : str , _snake_case : Optional[int] , _snake_case : Optional[Any] = None ) -> List[str]: """simple docstring""" lowerCamelCase_ : Dict = [self.sep_token_id] lowerCamelCase_ : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ (self : List[str] , _snake_case : Optional[int] , _snake_case : Dict = None ) -> int: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_A ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCamelCase_ : Any = os.path.join( _A , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_A ): copyfile(self.vocab_file , _A ) return (out_vocab_file,)
714
import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( '''The `image_to_image.py` script is outdated. Please use directly `from diffusers import''' ''' StableDiffusionImg2ImgPipeline` instead.''' )
144
0
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def __SCREAMING_SNAKE_CASE ( lowercase_ ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : int = [] embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight", f"stage{idx}.patch_embed.proj.weight", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias", f"stage{idx}.patch_embed.proj.bias", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight", f"stage{idx}.patch_embed.norm.weight", ) ) embed.append( ( f"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias", f"stage{idx}.patch_embed.norm.bias", ) ) return embed def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> List[Any]: '''simple docstring''' __UpperCAmelCase : Tuple = [] attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked", f"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight", f"stage{idx}.blocks.{cnt}.attn.proj_q.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias", f"stage{idx}.blocks.{cnt}.attn.proj_q.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight", f"stage{idx}.blocks.{cnt}.attn.proj_k.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias", f"stage{idx}.blocks.{cnt}.attn.proj_k.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight", f"stage{idx}.blocks.{cnt}.attn.proj_v.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias", f"stage{idx}.blocks.{cnt}.attn.proj_v.bias", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight", f"stage{idx}.blocks.{cnt}.attn.proj.weight", ) ) attention_weights.append( ( f"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias", f"stage{idx}.blocks.{cnt}.attn.proj.bias", ) ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc1.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc1.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight", f"stage{idx}.blocks.{cnt}.mlp.fc2.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias", f"stage{idx}.blocks.{cnt}.mlp.fc2.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight", f"stage{idx}.blocks.{cnt}.norm1.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias", f"stage{idx}.blocks.{cnt}.norm1.bias") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight", f"stage{idx}.blocks.{cnt}.norm2.weight") ) attention_weights.append( (f"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias", f"stage{idx}.blocks.{cnt}.norm2.bias") ) return attention_weights def __SCREAMING_SNAKE_CASE ( lowercase_ ) -> Any: '''simple docstring''' __UpperCAmelCase : List[Any] = [] token.append((f"cvt.encoder.stages.{idx}.cls_token", '''stage2.cls_token''') ) return token def __SCREAMING_SNAKE_CASE ( ) -> Tuple: '''simple docstring''' __UpperCAmelCase : Dict = [] head.append(('''layernorm.weight''', '''norm.weight''') ) head.append(('''layernorm.bias''', '''norm.bias''') ) head.append(('''classifier.weight''', '''head.weight''') ) head.append(('''classifier.bias''', '''head.bias''') ) return head def __SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> List[str]: '''simple docstring''' __UpperCAmelCase : Tuple = '''imagenet-1k-id2label.json''' __UpperCAmelCase : List[str] = 1000 __UpperCAmelCase : Tuple = '''huggingface/label-files''' __UpperCAmelCase : Tuple = num_labels __UpperCAmelCase : int = json.load(open(cached_download(hf_hub_url(lowercase_ , lowercase_ , repo_type='''dataset''' ) ) , '''r''' ) ) __UpperCAmelCase : Optional[Any] = {int(lowercase_ ): v for k, v in idalabel.items()} __UpperCAmelCase : Dict = idalabel __UpperCAmelCase : Optional[Any] = {v: k for k, v in idalabel.items()} __UpperCAmelCase : Optional[Any] = CvtConfig(num_labels=lowercase_ , idalabel=lowercase_ , labelaid=lowercase_ ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "13": __UpperCAmelCase : Any = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('''/''' , 1 )[-1][4:6] == "21": __UpperCAmelCase : Any = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __UpperCAmelCase : Optional[int] = [2, 2, 20] __UpperCAmelCase : str = [3, 12, 16] __UpperCAmelCase : str = [192, 768, 1024] __UpperCAmelCase : Optional[int] = CvtForImageClassification(lowercase_ ) __UpperCAmelCase : Tuple = AutoImageProcessor.from_pretrained('''facebook/convnext-base-224-22k-1k''' ) __UpperCAmelCase : Optional[Any] = image_size __UpperCAmelCase : Any = torch.load(lowercase_ , map_location=torch.device('''cpu''' ) ) __UpperCAmelCase : List[Any] = OrderedDict() __UpperCAmelCase : Optional[Any] = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __UpperCAmelCase : List[Any] = list_of_state_dict + cls_token(lowercase_ ) __UpperCAmelCase : Any = list_of_state_dict + embeddings(lowercase_ ) for cnt in range(config.depth[idx] ): __UpperCAmelCase : List[str] = list_of_state_dict + attention(lowercase_ , lowercase_ ) __UpperCAmelCase : List[Any] = list_of_state_dict + final() for gg in list_of_state_dict: print(lowercase_ ) for i in range(len(lowercase_ ) ): __UpperCAmelCase : Dict = original_weights[list_of_state_dict[i][1]] model.load_state_dict(lowercase_ ) model.save_pretrained(lowercase_ ) image_processor.save_pretrained(lowercase_ ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( """--cvt_model""", default="""cvt-w24""", type=str, help="""Name of the cvt model you'd like to convert.""", ) parser.add_argument( """--image_size""", default=384, type=int, help="""Input Image Size""", ) parser.add_argument( """--cvt_file_name""", default=R"""cvtmodels\CvT-w24-384x384-IN-22k.pth""", type=str, help="""Input Image Size""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowerCAmelCase = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
462
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class lowerCamelCase ( _UpperCamelCase , unittest.TestCase ): _lowerCAmelCase : Union[str, Any] = XLNetTokenizer _lowerCAmelCase : int = XLNetTokenizerFast _lowerCAmelCase : Optional[Any] = True _lowerCAmelCase : Optional[Any] = True def A( self): super().setUp() # We have a SentencePiece fixture for testing __UpperCAmelCase : Optional[Any] = XLNetTokenizer(lowercase__ , keep_accents=lowercase__) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname) def A( self): __UpperCAmelCase : Tuple = '''<s>''' __UpperCAmelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase__) , lowercase__) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase__) , lowercase__) def A( self): __UpperCAmelCase : Union[str, Any] = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<unk>''') self.assertEqual(vocab_keys[1] , '''<s>''') self.assertEqual(vocab_keys[-1] , '''<eod>''') self.assertEqual(len(lowercase__) , 1_0_0_6) def A( self): self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_0) def A( self): __UpperCAmelCase : List[str] = XLNetTokenizer(lowercase__ , keep_accents=lowercase__) __UpperCAmelCase : Optional[Any] = tokenizer.tokenize('''This is a test''') self.assertListEqual(lowercase__ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase__) , [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]) __UpperCAmelCase : Tuple = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( lowercase__ , [ 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 : Union[str, Any] = tokenizer.convert_tokens_to_ids(lowercase__) self.assertListEqual(lowercase__ , [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4]) __UpperCAmelCase : int = tokenizer.convert_ids_to_tokens(lowercase__) self.assertListEqual( lowercase__ , [ 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 A( self): __UpperCAmelCase : str = XLNetTokenizer(lowercase__ , do_lower_case=lowercase__) __UpperCAmelCase : int = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( lowercase__ , [ SPIECE_UNDERLINE + '''''', '''i''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''') , ['''▁he''', '''ll''', '''o''']) def A( self): __UpperCAmelCase : Optional[Any] = XLNetTokenizer(lowercase__ , do_lower_case=lowercase__) __UpperCAmelCase : Union[str, Any] = tokenizer.tokenize('''I was born in 92000, and this is falsé.''') self.assertListEqual( lowercase__ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) @slow def A( self): __UpperCAmelCase : Tuple = XLNetTokenizer.from_pretrained('''xlnet-base-cased''') __UpperCAmelCase : Optional[int] = tokenizer.encode('''sequence builders''' , add_special_tokens=lowercase__) __UpperCAmelCase : Optional[int] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=lowercase__) __UpperCAmelCase : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(lowercase__) __UpperCAmelCase : Optional[Any] = tokenizer.build_inputs_with_special_tokens(lowercase__ , lowercase__) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def A( self): # fmt: off __UpperCAmelCase : Optional[Any] = {'''input_ids''': [[1_7, 2_1_4_4_2, 2_7_0, 1_7, 1_0, 1_4_6_4_5, 3_1_8, 3_4, 1_7, 4_5_4_6, 3_1_4_5, 7_8_7, 1_3, 7_7_5_2, 2_2_0_1_8, 2_3, 2_1, 1_7, 4_5_4_6, 3_1_4_5, 7_8_7, 1_3, 3_3_5_2, 1_4_4_3_1, 1_3, 5_5_0_0, 1_1, 1_1_7_6, 5_8_0, 1_3, 1_6_8_1_9, 4_7_9_7, 2_3, 1_7, 1_0, 1_7_1_3_5, 6_5_8, 1_9, 4_5_7, 7_9_3_2, 1_3, 1_8_4, 1_9, 3_1_5_4, 1_7_1_3_5, 6_4_6_8, 1_9, 1_4_0_4, 1_2_2_6_9, 1_9, 4_2_2_9, 5_3_5_6, 1_6_2_6_4, 4_6, 1_9, 1_7, 2_0_5_4_5, 1_0_3_9_5, 9, 9, 9, 1_1, 2_8, 6_4_2_1, 9_5_3_1, 2_0_7_2_9, 1_7, 1_0, 3_5_3, 1_7_0_2_2, 1_1, 2_1, 6_4_2_1, 9_5_3_1, 1_6_9_4_9, 1_7, 1_0, 1_1_5_0_9, 7_5_3, 1_1, 3_3, 9_5, 2_4_2_1, 7_3_8_5, 9_5_6, 1_4_4_3_1, 2_6_2_6, 2_5, 8_4_2, 7_3_8_5, 4_8_3_6, 2_1, 1_4_2_9, 2_2_7_2, 9_8_5_5, 3_1_2_0, 1_6_1, 2_4_7_3_8, 1_9, 1_3_2_0_3, 6_5_8, 2_1_8, 7_8_7, 2_1, 4_3_0, 1_8_4_8_2, 8_4_7, 2_6_3_7, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_2_2, 2_2_1_7_8, 2_7, 1_0_6_4, 2_2, 9_5_6, 1_3, 1_1_1_0_1, 1_4_2_9, 5_8_5_4, 2_4_3_1_3, 1_8_9_5_3, 4_0, 4_2_2, 2_4_3_6_6, 6_8, 1_7_5_8, 3_7, 1_0_4_8_3, 1_4_2_5_7, 3_1, 2_0_7, 2_6_3, 2_1, 2_0_3, 3_7_7_3, 2_5, 7_1, 9_7_3_5, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_2, 2_0_4_9, 3_4_4_2, 1_7, 1_3_8_9_4, 3_3_8_0, 2_3, 9_5, 1_8, 1_7_6_3_4, 2_2_8_8, 9, 4, 3]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase__ , model_name='''xlnet-base-cased''' , revision='''c841166438c31ec7ca9a106dee7bb312b73ae511''' , )
462
1
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING lowerCamelCase__ = logging.get_logger(__name__) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :int = "upernet" def __init__( self : Optional[Any] , __a : Optional[Any]=None , __a : List[str]=512 , __a : List[Any]=0.02 , __a : Any=[1, 2, 3, 6] , __a : int=True , __a : Optional[Any]=0.4 , __a : List[Any]=384 , __a : Optional[Any]=256 , __a : Dict=1 , __a : Optional[int]=False , __a : List[str]=255 , **__a : Optional[Any] , ) -> Optional[int]: super().__init__(**UpperCAmelCase__ ) if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) _UpperCamelCase : int = CONFIG_MAPPING["resnet"](out_features=["stage1", "stage2", "stage3", "stage4"] ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): _UpperCamelCase : Union[str, Any] = backbone_config.get("model_type" ) _UpperCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] _UpperCamelCase : int = config_class.from_dict(UpperCAmelCase__ ) _UpperCamelCase : List[str] = backbone_config _UpperCamelCase : int = hidden_size _UpperCamelCase : Optional[int] = initializer_range _UpperCamelCase : str = pool_scales _UpperCamelCase : List[Any] = use_auxiliary_head _UpperCamelCase : List[str] = auxiliary_loss_weight _UpperCamelCase : Optional[Any] = auxiliary_in_channels _UpperCamelCase : Dict = auxiliary_channels _UpperCamelCase : List[Any] = auxiliary_num_convs _UpperCamelCase : Tuple = auxiliary_concat_input _UpperCamelCase : Optional[int] = loss_ignore_index def __SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: _UpperCamelCase : Tuple = copy.deepcopy(self.__dict__ ) _UpperCamelCase : Dict = self.backbone_config.to_dict() _UpperCamelCase : int = self.__class__.model_type return output
721
"""simple docstring""" import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = ["model.decoder.embed_positions.weights"] def lowercase__ ( lowercase_ ) -> Optional[Any]: """simple docstring""" if "emb" in name: _UpperCamelCase : List[str] = name.replace("emb" ,"model.decoder.embed_tokens" ) if "transformer" in name: _UpperCamelCase : Optional[int] = name.replace("transformer" ,"model.decoder" ) if "cross_attention" in name: _UpperCamelCase : Optional[int] = name.replace("cross_attention" ,"encoder_attn" ) if "linear1" in name: _UpperCamelCase : Optional[Any] = name.replace("linear1" ,"fc1" ) if "linear2" in name: _UpperCamelCase : Union[str, Any] = name.replace("linear2" ,"fc2" ) if "norm1" in name: _UpperCamelCase : Optional[Any] = name.replace("norm1" ,"self_attn_layer_norm" ) if "norm_cross" in name: _UpperCamelCase : Dict = name.replace("norm_cross" ,"encoder_attn_layer_norm" ) if "norm2" in name: _UpperCamelCase : Union[str, Any] = name.replace("norm2" ,"final_layer_norm" ) if "out_norm" in name: _UpperCamelCase : Union[str, Any] = name.replace("out_norm" ,"model.decoder.layer_norm" ) if "linears" in name: _UpperCamelCase : List[str] = name.replace("linears" ,"lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: _UpperCamelCase : Any = name.replace("condition_provider.conditioners.description.output_proj" ,"enc_to_dec_proj" ) return name def lowercase__ ( lowercase_ ,lowercase_ ) -> Tuple[Dict, Dict]: """simple docstring""" _UpperCamelCase : str = list(state_dict.keys() ) _UpperCamelCase : Optional[Any] = {} for key in keys: _UpperCamelCase : Optional[int] = state_dict.pop(lowercase_ ) _UpperCamelCase : List[Any] = rename_keys(lowercase_ ) if "in_proj_weight" in key: # split fused qkv proj _UpperCamelCase : Tuple = val[:hidden_size, :] _UpperCamelCase : Optional[Any] = val[hidden_size : 2 * hidden_size, :] _UpperCamelCase : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: _UpperCamelCase : Optional[Any] = val else: _UpperCamelCase : List[str] = val return state_dict, enc_dec_proj_state_dict def lowercase__ ( lowercase_ ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values _UpperCamelCase : List[Any] = 1_024 _UpperCamelCase : List[str] = 24 _UpperCamelCase : Any = 16 elif checkpoint == "medium": _UpperCamelCase : Tuple = 1_536 _UpperCamelCase : Dict = 48 _UpperCamelCase : Tuple = 24 elif checkpoint == "large": _UpperCamelCase : int = 2_048 _UpperCamelCase : Optional[int] = 48 _UpperCamelCase : Dict = 32 else: raise ValueError(F'''Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.''' ) _UpperCamelCase : str = MusicgenDecoderConfig( hidden_size=lowercase_ ,ffn_dim=hidden_size * 4 ,num_hidden_layers=lowercase_ ,num_attention_heads=lowercase_ ,) return config @torch.no_grad() def lowercase__ ( lowercase_ ,lowercase_=None ,lowercase_=None ,lowercase_="cpu" ) -> List[str]: """simple docstring""" _UpperCamelCase : str = MusicGen.get_pretrained(lowercase_ ,device=lowercase_ ) _UpperCamelCase : Union[str, Any] = decoder_config_from_checkpoint(lowercase_ ) _UpperCamelCase : Optional[int] = fairseq_model.lm.state_dict() _UpperCamelCase, _UpperCamelCase : Optional[Any] = rename_state_dict( lowercase_ ,hidden_size=decoder_config.hidden_size ) _UpperCamelCase : Tuple = TaEncoderModel.from_pretrained("t5-base" ) _UpperCamelCase : Union[str, Any] = EncodecModel.from_pretrained("facebook/encodec_32khz" ) _UpperCamelCase : str = MusicgenForCausalLM(lowercase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection _UpperCamelCase, _UpperCamelCase : str = decoder.load_state_dict(lowercase_ ,strict=lowercase_ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(lowercase_ ) if len(lowercase_ ) > 0: raise ValueError(F'''Missing key(s) in state_dict: {missing_keys}''' ) if len(lowercase_ ) > 0: raise ValueError(F'''Unexpected key(s) in state_dict: {unexpected_keys}''' ) # init the composite model _UpperCamelCase : str = MusicgenForConditionalGeneration(text_encoder=lowercase_ ,audio_encoder=lowercase_ ,decoder=lowercase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(lowercase_ ) # check we can do a forward pass _UpperCamelCase : List[str] = torch.arange(0 ,8 ,dtype=torch.long ).reshape(2 ,-1 ) _UpperCamelCase : Dict = input_ids.reshape(2 * 4 ,-1 ) with torch.no_grad(): _UpperCamelCase : Tuple = model(input_ids=lowercase_ ,decoder_input_ids=lowercase_ ).logits if logits.shape != (8, 1, 2_048): raise ValueError("Incorrect shape for logits" ) # now construct the processor _UpperCamelCase : int = AutoTokenizer.from_pretrained("t5-base" ) _UpperCamelCase : str = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" ,padding_side="left" ) _UpperCamelCase : Optional[int] = MusicgenProcessor(feature_extractor=lowercase_ ,tokenizer=lowercase_ ) # set the appropriate bos/pad token ids _UpperCamelCase : str = 2_048 _UpperCamelCase : str = 2_048 # set other default generation config params _UpperCamelCase : Optional[Any] = int(30 * audio_encoder.config.frame_rate ) _UpperCamelCase : List[str] = True _UpperCamelCase : int = 3.0 if pytorch_dump_folder is not None: Path(lowercase_ ).mkdir(exist_ok=lowercase_ ) logger.info(F'''Saving model {checkpoint} to {pytorch_dump_folder}''' ) model.save_pretrained(lowercase_ ) processor.save_pretrained(lowercase_ ) if repo_id: logger.info(F'''Pushing model {checkpoint} to {repo_id}''' ) model.push_to_hub(lowercase_ ) processor.push_to_hub(lowercase_ ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) lowerCamelCase__ = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
51
0
from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig 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 TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : """simple docstring""" def __init__( self : Optional[Any] , lowerCamelCase__ : Dict , lowerCamelCase__ : str=3 , lowerCamelCase__ : Dict=32 , lowerCamelCase__ : Dict=3 , lowerCamelCase__ : str=10 , lowerCamelCase__ : Tuple=[10, 20, 30, 40] , lowerCamelCase__ : Tuple=[1, 1, 2, 1] , lowerCamelCase__ : str=True , lowerCamelCase__ : List[str]=True , lowerCamelCase__ : Tuple="relu" , lowerCamelCase__ : List[str]=3 , lowerCamelCase__ : int=None , ): a__ : Optional[Any] = parent a__ : Optional[int] = batch_size a__ : Union[str, Any] = image_size a__ : Dict = num_channels a__ : Any = embeddings_size a__ : int = hidden_sizes a__ : Optional[int] = depths a__ : List[str] = is_training a__ : Dict = use_labels a__ : int = hidden_act a__ : Tuple = num_labels a__ : Tuple = scope a__ : str = len(lowerCamelCase__ ) def _UpperCamelCase( self : int ): a__ : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a__ : Union[str, Any] = None if self.use_labels: a__ : Dict = ids_tensor([self.batch_size] , self.num_labels ) a__ : Any = self.get_config() return config, pixel_values, labels def _UpperCamelCase( self : Optional[Any] ): return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _UpperCamelCase( self : Any , lowerCamelCase__ : Any , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Any ): a__ : str = TFResNetModel(config=lowerCamelCase__ ) a__ : Union[str, Any] = model(lowerCamelCase__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _UpperCamelCase( self : int , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Optional[int] ): a__ : List[str] = self.num_labels a__ : Any = TFResNetForImageClassification(lowerCamelCase__ ) a__ : Dict = model(lowerCamelCase__ , labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase( self : Optional[Any] ): a__ : Any = self.prepare_config_and_inputs() a__, a__, a__ : Union[str, Any] = config_and_inputs a__ : int = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class A__ ( A__ , A__ , unittest.TestCase ): """simple docstring""" _lowercase = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () _lowercase = ( {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification} if is_tf_available() else {} ) _lowercase = False _lowercase = False _lowercase = False _lowercase = False _lowercase = False def _UpperCamelCase( self : Any ): a__ : Tuple = TFResNetModelTester(self ) a__ : Any = ConfigTester(self , config_class=lowerCamelCase__ , has_text_modality=lowerCamelCase__ ) def _UpperCamelCase( self : int ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _UpperCamelCase( self : Any ): return @unittest.skip(reason="ResNet does not use inputs_embeds" ) def _UpperCamelCase( self : Optional[Any] ): pass @unittest.skip(reason="ResNet does not support input and output embeddings" ) def _UpperCamelCase( self : Any ): pass def _UpperCamelCase( self : Union[str, Any] ): a__, a__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a__ : Tuple = model_class(lowerCamelCase__ ) a__ : Any = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a__ : Tuple = [*signature.parameters.keys()] a__ : str = ["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 ): def check_hidden_states_output(lowerCamelCase__ : Any , lowerCamelCase__ : Any , lowerCamelCase__ : str ): a__ : Optional[int] = model_class(lowerCamelCase__ ) a__ : Optional[int] = model(**self._prepare_for_class(lowerCamelCase__ , lowerCamelCase__ ) ) a__ : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states a__ : str = self.model_tester.num_stages self.assertEqual(len(lowerCamelCase__ ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) a__, a__ : str = self.model_tester.prepare_config_and_inputs_for_common() a__ : str = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: a__ : Optional[int] = layer_type a__ : List[str] = True check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] a__ : List[Any] = True check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) def _UpperCamelCase( self : Optional[Any] ): a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__ ) @slow def _UpperCamelCase( self : Dict ): for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : List[str] = TFResNetModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) def UpperCamelCase_ ( ) -> Tuple: a__ : Any = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class A__ ( unittest.TestCase ): """simple docstring""" @cached_property def _UpperCamelCase( self : int ): return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def _UpperCamelCase( self : Dict ): a__ : List[str] = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) a__ : Union[str, Any] = self.default_image_processor a__ : Optional[Any] = prepare_img() a__ : Dict = image_processor(images=lowerCamelCase__ , return_tensors="tf" ) # forward pass a__ : Optional[int] = model(**lowerCamelCase__ ) # verify the logits a__ : Union[str, Any] = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase__ ) a__ : Union[str, Any] = tf.constant([-11.1069, -9.7877, -8.3777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , lowerCamelCase__ , atol=1E-4 ) )
37
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
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging lowercase = logging.get_logger(__name__) def _lowerCAmelCase ( __lowerCamelCase:Union[tf.Tensor, np.ndarray] ): '''simple docstring''' if isinstance(__lowerCamelCase , np.ndarray ): return list(tensor.shape ) __magic_name__ = tf.shape(__lowerCamelCase ) if tensor.shape == tf.TensorShape(__lowerCamelCase ): return dynamic __magic_name__ = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(__lowerCamelCase )] def _lowerCAmelCase ( __lowerCamelCase:tf.Tensor , __lowerCamelCase:Optional[int] = None , __lowerCamelCase:Optional[str] = None ): '''simple docstring''' return tf.nn.softmax(logits=logits + 1E-9 , axis=__lowerCamelCase , name=__lowerCamelCase ) def _lowerCAmelCase ( __lowerCamelCase:Optional[int] , __lowerCamelCase:List[Any] , __lowerCamelCase:Tuple , __lowerCamelCase:Optional[int]=1E-5 , __lowerCamelCase:Optional[int]=-1 ): '''simple docstring''' if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(__lowerCamelCase , __lowerCamelCase ): raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis." ) # Get mean and variance on the axis to be normalized __magic_name__ , __magic_name__ = tf.nn.moments(__lowerCamelCase , axes=[axis] , keepdims=__lowerCamelCase ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis __magic_name__ = [1] * inputs.shape.rank __magic_name__ = shape_list(__lowerCamelCase )[axis] __magic_name__ = tf.reshape(__lowerCamelCase , __lowerCamelCase ) __magic_name__ = tf.reshape(__lowerCamelCase , __lowerCamelCase ) # Compute layer normalization using the batch_normalization # function. __magic_name__ = tf.nn.batch_normalization( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , offset=__lowerCamelCase , scale=__lowerCamelCase , variance_epsilon=__lowerCamelCase , ) return outputs def _lowerCAmelCase ( __lowerCamelCase:int , __lowerCamelCase:Any=0 , __lowerCamelCase:str=-1 ): '''simple docstring''' if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input __magic_name__ = tf.shape(__lowerCamelCase ) __magic_name__ = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) __magic_name__ = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(__lowerCamelCase , __lowerCamelCase ) def _lowerCAmelCase ( __lowerCamelCase:tf.Tensor ): '''simple docstring''' if not isinstance(__lowerCamelCase , tf.Tensor ): __magic_name__ = tf.convert_to_tensor(__lowerCamelCase ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: __magic_name__ = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: __magic_name__ = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) __magic_name__ = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def _lowerCAmelCase ( __lowerCamelCase:tf.Tensor , __lowerCamelCase:int , __lowerCamelCase:str = "input_ids" ): '''simple docstring''' tf.debugging.assert_less( __lowerCamelCase , tf.cast(__lowerCamelCase , dtype=tensor.dtype ) , message=( f'''The maximum value of {tensor_name} ({tf.math.reduce_max(__lowerCamelCase )}) must be smaller than the embedding ''' f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def _lowerCAmelCase ( __lowerCamelCase:List[str] , __lowerCamelCase:Optional[int] , __lowerCamelCase:int ): '''simple docstring''' __magic_name__ = 6_4_5_1_2 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. __magic_name__ = [x for x in data if len(__lowerCamelCase ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( "The following attributes cannot be saved to HDF5 file because " f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' f'''bytes: {bad_attributes}''' ) __magic_name__ = np.asarray(__lowerCamelCase ) __magic_name__ = 1 __magic_name__ = np.array_split(__lowerCamelCase , __lowerCamelCase ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 __magic_name__ = np.array_split(__lowerCamelCase , __lowerCamelCase ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(__lowerCamelCase ): __magic_name__ = chunk_data else: __magic_name__ = data def _lowerCAmelCase ( __lowerCamelCase:int , __lowerCamelCase:Tuple ): '''simple docstring''' if name in group.attrs: __magic_name__ = [n.decode("utf8" ) if hasattr(__lowerCamelCase , "decode" ) else n for n in group.attrs[name]] else: __magic_name__ = [] __magic_name__ = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("utf8" ) if hasattr(__lowerCamelCase , "decode" ) else n for n in group.attrs["%s%d" % (name, chunk_id)]] ) chunk_id += 1 return data def _lowerCAmelCase ( __lowerCamelCase:List[str] ): '''simple docstring''' def _expand_single_ad_tensor(__lowerCamelCase:List[Any] ): if isinstance(__lowerCamelCase , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(__lowerCamelCase , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , __lowerCamelCase )
468
"""simple docstring""" from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow 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 TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class A_ : def __init__( self : List[str] , __lowerCamelCase : str , __lowerCamelCase : Dict=1_3 , __lowerCamelCase : int=3_0 , __lowerCamelCase : List[Any]=2 , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : int=3_2 , __lowerCamelCase : int=2 , __lowerCamelCase : Optional[Any]=4 , __lowerCamelCase : List[str]=3_7 , __lowerCamelCase : List[str]="gelu" , __lowerCamelCase : Tuple=0.1 , __lowerCamelCase : int=0.1 , __lowerCamelCase : Optional[int]=1_0 , __lowerCamelCase : Tuple=0.02 , __lowerCamelCase : Any=3 , __lowerCamelCase : Union[str, Any]=0.6 , __lowerCamelCase : Optional[int]=None , ) -> Union[str, Any]: __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = image_size __magic_name__ = patch_size __magic_name__ = num_channels __magic_name__ = is_training __magic_name__ = use_labels __magic_name__ = hidden_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = mask_ratio __magic_name__ = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) __magic_name__ = (image_size // patch_size) ** 2 __magic_name__ = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def _snake_case ( self : Optional[Any] ) -> List[Any]: __magic_name__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = self.get_config() return config, pixel_values, labels def _snake_case ( self : Optional[int] ) -> Dict: return ViTMAEConfig( 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 , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_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 , mask_ratio=self.mask_ratio , ) def _snake_case ( self : Tuple , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[int] ) -> Optional[int]: __magic_name__ = TFViTMAEModel(config=__lowerCamelCase ) __magic_name__ = model(__lowerCamelCase , training=__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : str ) -> Union[str, Any]: __magic_name__ = TFViTMAEForPreTraining(__lowerCamelCase ) __magic_name__ = model(__lowerCamelCase , training=__lowerCamelCase ) # expected sequence length = num_patches __magic_name__ = (self.image_size // self.patch_size) ** 2 __magic_name__ = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images __magic_name__ = 1 __magic_name__ = TFViTMAEForPreTraining(__lowerCamelCase ) __magic_name__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __magic_name__ = model(__lowerCamelCase , training=__lowerCamelCase ) __magic_name__ = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def _snake_case ( self : Tuple ) -> Optional[Any]: __magic_name__ = self.prepare_config_and_inputs() ((__magic_name__) , (__magic_name__) , (__magic_name__)) = config_and_inputs __magic_name__ = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class A_ ( snake_case_ , snake_case_ , unittest.TestCase ): UpperCAmelCase__ = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () UpperCAmelCase__ = {'''feature-extraction''': TFViTMAEModel} if is_tf_available() else {} UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False UpperCAmelCase__ = False def _snake_case ( self : Any ) -> int: __magic_name__ = TFViTMAEModelTester(self ) __magic_name__ = ConfigTester(self , config_class=__lowerCamelCase , has_text_modality=__lowerCamelCase , hidden_size=3_7 ) def _snake_case ( self : Dict ) -> Any: self.config_tester.run_common_tests() @unittest.skip(reason="ViTMAE does not use inputs_embeds" ) def _snake_case ( self : Any ) -> Optional[Any]: pass def _snake_case ( self : Optional[Any] ) -> Tuple: __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __magic_name__ = model_class(__lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) __magic_name__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCamelCase , tf.keras.layers.Layer ) ) def _snake_case ( self : Optional[Any] ) -> Optional[Any]: __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __magic_name__ = model_class(__lowerCamelCase ) __magic_name__ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __magic_name__ = [*signature.parameters.keys()] __magic_name__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , __lowerCamelCase ) def _snake_case ( self : int ) -> Union[str, Any]: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : str ) -> Any: __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__lowerCamelCase ) def _snake_case ( self : str ) -> List[Any]: # make the mask reproducible np.random.seed(2 ) __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ = int((config.image_size // config.patch_size) ** 2 ) __magic_name__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: __magic_name__ = model_class(__lowerCamelCase ) __magic_name__ = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) __magic_name__ = model(__lowerCamelCase , noise=__lowerCamelCase ) __magic_name__ = copy.deepcopy(self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) ) __magic_name__ = model(**__lowerCamelCase , noise=__lowerCamelCase ) __magic_name__ = outputs_dict[0].numpy() __magic_name__ = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1e-6 ) def _snake_case ( self : int ) -> Union[str, Any]: # make the mask reproducible np.random.seed(2 ) __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ = int((config.image_size // config.patch_size) ** 2 ) __magic_name__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(__lowerCamelCase : Tuple ): __magic_name__ = {} for k, v in inputs_dict.items(): if tf.is_tensor(__lowerCamelCase ): __magic_name__ = v.numpy() else: __magic_name__ = np.array(__lowerCamelCase ) return inputs_np_dict for model_class in self.all_model_classes: __magic_name__ = model_class(__lowerCamelCase ) __magic_name__ = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) __magic_name__ = prepare_numpy_arrays(__lowerCamelCase ) __magic_name__ = model(__lowerCamelCase , noise=__lowerCamelCase ) __magic_name__ = model(**__lowerCamelCase , noise=__lowerCamelCase ) self.assert_outputs_same(__lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : int , __lowerCamelCase : Optional[int] , __lowerCamelCase : Any , __lowerCamelCase : Dict ) -> List[Any]: # make masks reproducible np.random.seed(2 ) __magic_name__ = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) __magic_name__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) __magic_name__ = tf.constant(__lowerCamelCase ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument __magic_name__ = tf_noise super().check_pt_tf_models(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def _snake_case ( self : List[Any] ) -> List[str]: # make mask reproducible np.random.seed(2 ) __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(__lowerCamelCase ) if module_member_name.endswith("MainLayer" ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len("MainLayer" )] == model_class.__name__[: -len("Model" )] for module_member in (getattr(__lowerCamelCase , __lowerCamelCase ),) if isinstance(__lowerCamelCase , __lowerCamelCase ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(__lowerCamelCase , "_keras_serializable" , __lowerCamelCase ) } __magic_name__ = int((config.image_size // config.patch_size) ** 2 ) __magic_name__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) __magic_name__ = tf.convert_to_tensor(__lowerCamelCase ) inputs_dict.update({"noise": noise} ) for main_layer_class in tf_main_layer_classes: __magic_name__ = main_layer_class(__lowerCamelCase ) __magic_name__ = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } __magic_name__ = tf.keras.Model(__lowerCamelCase , outputs=main_layer(__lowerCamelCase ) ) __magic_name__ = model(__lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __magic_name__ = os.path.join(__lowerCamelCase , "keras_model.h5" ) model.save(__lowerCamelCase ) __magic_name__ = tf.keras.models.load_model( __lowerCamelCase , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(__lowerCamelCase , tf.keras.Model ) __magic_name__ = model(__lowerCamelCase ) self.assert_outputs_same(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : Union[str, Any] ) -> str: # make mask reproducible np.random.seed(2 ) __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ = int((config.image_size // config.patch_size) ** 2 ) __magic_name__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: __magic_name__ = model_class(__lowerCamelCase ) __magic_name__ = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) __magic_name__ = model(__lowerCamelCase , noise=__lowerCamelCase ) if model_class.__name__ == "TFViTMAEModel": __magic_name__ = outputs.last_hidden_state.numpy() __magic_name__ = 0 else: __magic_name__ = outputs.logits.numpy() __magic_name__ = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__lowerCamelCase , saved_model=__lowerCamelCase ) __magic_name__ = model_class.from_pretrained(__lowerCamelCase ) __magic_name__ = model(__lowerCamelCase , noise=__lowerCamelCase ) if model_class.__name__ == "TFViTMAEModel": __magic_name__ = after_outputs["last_hidden_state"].numpy() __magic_name__ = 0 else: __magic_name__ = after_outputs["logits"].numpy() __magic_name__ = 0 __magic_name__ = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(__lowerCamelCase , 1e-5 ) def _snake_case ( self : List[str] ) -> Optional[Any]: # make mask reproducible np.random.seed(2 ) __magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common() __magic_name__ = int((config.image_size // config.patch_size) ** 2 ) __magic_name__ = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: __magic_name__ = model_class(__lowerCamelCase ) __magic_name__ = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) __magic_name__ = model(__lowerCamelCase , noise=__lowerCamelCase ) __magic_name__ = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(__lowerCamelCase ) __magic_name__ = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config __magic_name__ = model_class.from_config(model.config ) __magic_name__ = new_model(__lowerCamelCase ) # Build model new_model.set_weights(model.get_weights() ) __magic_name__ = new_model(__lowerCamelCase , noise=__lowerCamelCase ) self.assert_outputs_same(__lowerCamelCase , __lowerCamelCase ) @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def _snake_case ( self : str ) -> List[Any]: pass @unittest.skip(reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load" ) def _snake_case ( self : Any ) -> List[str]: pass @slow def _snake_case ( self : List[Any] ) -> Any: __magic_name__ = TFViTMAEModel.from_pretrained("google/vit-base-patch16-224" ) self.assertIsNotNone(__lowerCamelCase ) def _lowerCAmelCase ( ): '''simple docstring''' __magic_name__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class A_ ( unittest.TestCase ): @cached_property def _snake_case ( self : Union[str, Any] ) -> Union[str, Any]: return ViTImageProcessor.from_pretrained("facebook/vit-mae-base" ) if is_vision_available() else None @slow def _snake_case ( self : Union[str, Any] ) -> Union[str, Any]: # make random mask reproducible across the PT and TF model np.random.seed(2 ) __magic_name__ = TFViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base" ) __magic_name__ = self.default_image_processor __magic_name__ = prepare_img() __magic_name__ = image_processor(images=__lowerCamelCase , return_tensors="tf" ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) __magic_name__ = ViTMAEConfig() __magic_name__ = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) __magic_name__ = np.random.uniform(size=(1, num_patches) ) # forward pass __magic_name__ = model(**__lowerCamelCase , noise=__lowerCamelCase ) # verify the logits __magic_name__ = tf.convert_to_tensor([1, 1_9_6, 7_6_8] ) self.assertEqual(outputs.logits.shape , __lowerCamelCase ) __magic_name__ = tf.convert_to_tensor( [[-0.0548, -1.7023, -0.9325], [0.3721, -0.5670, -0.2233], [0.8235, -1.3878, -0.3524]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , __lowerCamelCase , atol=1e-4 )
468
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase : Tuple = """▁""" lowerCAmelCase : int = {"""vocab_file""": """spiece.model"""} lowerCAmelCase : Any = { """vocab_file""": {"""google/pegasus-xsum""": """https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model"""} } lowerCAmelCase : Tuple = { """google/pegasus-xsum""": 512, } lowerCAmelCase : List[str] = logging.get_logger(__name__) class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self , _a , _a="<pad>" , _a="</s>" , _a="<unk>" , _a="<mask_2>" , _a="<mask_1>" , _a=None , _a=103 , _a = None , **_a , ): """simple docstring""" lowerCamelCase = offset if additional_special_tokens is not None: if not isinstance(_a , _a ): raise TypeError( f'additional_special_tokens should be of type {type(_a )}, but is' f' {type(_a )}' ) lowerCamelCase = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ f'<unk_{i}>' for i in range(len(_a ) , self.offset - 1 ) ] if len(set(_a ) ) != len(_a ): raise ValueError( """Please make sure that the provided additional_special_tokens do not contain an incorrectly""" f' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' ) lowerCamelCase = additional_special_tokens_extended else: lowerCamelCase = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [f'<unk_{i}>' for i in range(2 , self.offset )] lowerCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_a , unk_token=_a , mask_token=_a , pad_token=_a , mask_token_sent=_a , offset=_a , additional_special_tokens=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) lowerCamelCase = mask_token_sent lowerCamelCase = vocab_file lowerCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_a ) # add special tokens to encoder dict lowerCamelCase = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 , self.offset - 1 )} ) lowerCamelCase = {v: k for k, v in self.encoder.items()} @property def _lowerCAmelCase ( self ): """simple docstring""" return len(self.sp_model ) + self.offset def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowerCamelCase = self.__dict__.copy() lowerCamelCase = None return state def __setstate__( self , _a ): """simple docstring""" lowerCamelCase = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCamelCase = {} lowerCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _lowerCAmelCase ( self , _a ): """simple docstring""" return self.sp_model.encode(_a , out_type=_a ) def _lowerCAmelCase ( self , _a ): """simple docstring""" if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] lowerCamelCase = self.sp_model.piece_to_id(_a ) return sp_id + self.offset def _lowerCAmelCase ( self , _a ): """simple docstring""" if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: lowerCamelCase = self.sp_model.IdToPiece(index - self.offset ) return token def _lowerCAmelCase ( self , _a ): """simple docstring""" lowerCamelCase = [] lowerCamelCase = """""" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(_a ) + token lowerCamelCase = [] else: current_sub_tokens.append(_a ) out_string += self.sp_model.decode(_a ) return out_string.strip() def _lowerCAmelCase ( self , _a=False ): """simple docstring""" return 1 def _lowerCAmelCase ( self , _a ): """simple docstring""" lowerCamelCase = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def _lowerCAmelCase ( self , _a , _a = None , _a = False ): """simple docstring""" if already_has_special_tokens: return self._special_token_mask(_a ) elif token_ids_a is None: return self._special_token_mask(_a ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def _lowerCAmelCase ( self , _a , _a=None ): """simple docstring""" if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def _lowerCAmelCase ( self , _a , _a = None ): """simple docstring""" if not os.path.isdir(_a ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCamelCase = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , """wb""" ) as fi: lowerCamelCase = self.sp_model.serialized_model_proto() fi.write(_a ) return (out_vocab_file,)
543
"""simple docstring""" import random def a__ ( snake_case__ , snake_case__ , snake_case__ = False ) -> dict: lowerCamelCase = {i: [] for i in range(snake_case__ )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(snake_case__ ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(snake_case__ ): for j in range(i + 1 , snake_case__ ): if random.random() < probability: graph[i].append(snake_case__ ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(snake_case__ ) return graph def a__ ( snake_case__ ) -> dict: return { i: [j for j in range(snake_case__ ) if i != j] for i in range(snake_case__ ) } if __name__ == "__main__": import doctest doctest.testmod()
543
1
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __UpperCAmelCase =sys.version_info >= (3, 10) def __a ( A=None , A=None ) -> List[str]: '''simple docstring''' return field(default_factory=lambda: default , metadata=A ) @dataclass class lowerCAmelCase__ : lowercase__ : int lowercase__ : float lowercase__ : str lowercase__ : bool @dataclass class lowerCAmelCase__ : lowercase__ : int = 42 lowercase__ : str = field(default="""toto""" , metadata={"""help""": """help message"""} ) @dataclass class lowerCAmelCase__ : lowercase__ : bool = False lowercase__ : bool = True lowercase__ : Optional[bool] = None class lowerCAmelCase__ ( UpperCAmelCase_ ): lowercase__ : Dict = """titi""" lowercase__ : Dict = """toto""" class lowerCAmelCase__ ( UpperCAmelCase_ ): lowercase__ : Union[str, Any] = """titi""" lowercase__ : str = """toto""" lowercase__ : Optional[int] = 42 @dataclass class lowerCAmelCase__ : lowercase__ : BasicEnum = "toto" def lowercase_ ( self ): '''simple docstring''' A__ = BasicEnum(self.foo ) @dataclass class lowerCAmelCase__ : lowercase__ : MixedTypeEnum = "toto" def lowercase_ ( self ): '''simple docstring''' A__ = MixedTypeEnum(self.foo ) @dataclass class lowerCAmelCase__ : lowercase__ : Optional[int] = None lowercase__ : Optional[float] = field(default=UpperCAmelCase_ , metadata={"""help""": """help message"""} ) lowercase__ : Optional[str] = None lowercase__ : Optional[List[str]] = list_field(default=[] ) lowercase__ : Optional[List[int]] = list_field(default=[] ) @dataclass class lowerCAmelCase__ : lowercase__ : List[int] = list_field(default=[] ) lowercase__ : List[int] = list_field(default=[1, 2, 3] ) lowercase__ : List[str] = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] ) lowercase__ : List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class lowerCAmelCase__ : lowercase__ : List[int] = field() lowercase__ : str = field() lowercase__ : BasicEnum = field() def lowercase_ ( self ): '''simple docstring''' A__ = BasicEnum(self.required_enum ) @dataclass class lowerCAmelCase__ : lowercase__ : int lowercase__ : "BasicEnum" = field() lowercase__ : "Optional[bool]" = None lowercase__ : "str" = field(default="""toto""" , metadata={"""help""": """help message"""} ) lowercase__ : "List[str]" = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] ) if is_python_no_less_than_3_10: @dataclass class lowerCAmelCase__ : lowercase__ : bool = False lowercase__ : bool = True lowercase__ : bool | None = None @dataclass class lowerCAmelCase__ : lowercase__ : int | None = None lowercase__ : float | None = field(default=UpperCAmelCase_ , metadata={"""help""": """help message"""} ) lowercase__ : str | None = None lowercase__ : list[str] | None = list_field(default=[] ) lowercase__ : list[int] | None = list_field(default=[] ) class lowerCAmelCase__ ( unittest.TestCase ): def lowercase_ ( self , UpperCamelCase__ , UpperCamelCase__ ): '''simple docstring''' self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): A__ = {k: v for k, v in vars(UpperCamelCase__ ).items() if k != "container"} A__ = {k: v for k, v in vars(UpperCamelCase__ ).items() if k != "container"} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("choices" , UpperCamelCase__ ) and yy.get("choices" , UpperCamelCase__ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["type"](UpperCamelCase__ ) , yy["type"](UpperCamelCase__ ) ) del xx["type"], yy["type"] self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=UpperCamelCase__ , required=UpperCamelCase__ ) expected.add_argument("--bar" , type=UpperCamelCase__ , required=UpperCamelCase__ ) expected.add_argument("--baz" , type=UpperCamelCase__ , required=UpperCamelCase__ ) expected.add_argument("--flag" , type=UpperCamelCase__ , default=UpperCamelCase__ , const=UpperCamelCase__ , nargs="?" ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) A__ = ["--foo", "1", "--baz", "quux", "--bar", "0.5"] ((A__) , ) = parser.parse_args_into_dataclasses(UpperCamelCase__ , look_for_args_file=UpperCamelCase__ ) self.assertFalse(example.flag ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=42 , type=UpperCamelCase__ ) expected.add_argument("--baz" , default="toto" , type=UpperCamelCase__ , help="help message" ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' A__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=UpperCamelCase__ , default=UpperCamelCase__ , const=UpperCamelCase__ , nargs="?" ) expected.add_argument("--baz" , type=UpperCamelCase__ , default=UpperCamelCase__ , const=UpperCamelCase__ , nargs="?" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("--no_baz" , action="store_false" , default=UpperCamelCase__ , dest="baz" ) expected.add_argument("--opt" , type=UpperCamelCase__ , default=UpperCamelCase__ ) A__ = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCamelCase__ ) for dataclass_type in dataclass_types: A__ = HfArgumentParser(UpperCamelCase__ ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) A__ = parser.parse_args([] ) self.assertEqual(UpperCamelCase__ , Namespace(foo=UpperCamelCase__ , baz=UpperCamelCase__ , opt=UpperCamelCase__ ) ) A__ = parser.parse_args(["--foo", "--no_baz"] ) self.assertEqual(UpperCamelCase__ , Namespace(foo=UpperCamelCase__ , baz=UpperCamelCase__ , opt=UpperCamelCase__ ) ) A__ = parser.parse_args(["--foo", "--baz"] ) self.assertEqual(UpperCamelCase__ , Namespace(foo=UpperCamelCase__ , baz=UpperCamelCase__ , opt=UpperCamelCase__ ) ) A__ = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"] ) self.assertEqual(UpperCamelCase__ , Namespace(foo=UpperCamelCase__ , baz=UpperCamelCase__ , opt=UpperCamelCase__ ) ) A__ = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"] ) self.assertEqual(UpperCamelCase__ , Namespace(foo=UpperCamelCase__ , baz=UpperCamelCase__ , opt=UpperCamelCase__ ) ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=["titi", "toto", 42] , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) A__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) A__ = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) A__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) A__ = parser.parse_args_into_dataclasses(["--foo", "titi"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) A__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) A__ = parser.parse_args_into_dataclasses(["--foo", "42"] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def lowercase_ ( self ): '''simple docstring''' @dataclass class lowerCAmelCase__ : lowercase__ : Literal["titi", "toto", 42] = "toto" A__ = HfArgumentParser(UpperCamelCase__ ) A__ = argparse.ArgumentParser() expected.add_argument( "--foo" , default="toto" , choices=("titi", "toto", 42) , type=make_choice_type_function(["titi", "toto", 42] ) , ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) A__ = parser.parse_args([] ) self.assertEqual(args.foo , "toto" ) A__ = parser.parse_args(["--foo", "titi"] ) self.assertEqual(args.foo , "titi" ) A__ = parser.parse_args(["--foo", "42"] ) self.assertEqual(args.foo , 42 ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = argparse.ArgumentParser() expected.add_argument("--foo_int" , nargs="+" , default=[] , type=UpperCamelCase__ ) expected.add_argument("--bar_int" , nargs="+" , default=[1, 2, 3] , type=UpperCamelCase__ ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=UpperCamelCase__ ) expected.add_argument("--foo_float" , nargs="+" , default=[0.1, 0.2, 0.3] , type=UpperCamelCase__ ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) A__ = parser.parse_args([] ) self.assertEqual( UpperCamelCase__ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["Hallo", "Bonjour", "Hello"] , foo_float=[0.1, 0.2, 0.3] ) , ) A__ = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split() ) self.assertEqual(UpperCamelCase__ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["a", "b", "c"] , foo_float=[0.1, 0.7] ) ) def lowercase_ ( self ): '''simple docstring''' A__ = argparse.ArgumentParser() expected.add_argument("--foo" , default=UpperCamelCase__ , type=UpperCamelCase__ ) expected.add_argument("--bar" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="help message" ) expected.add_argument("--baz" , default=UpperCamelCase__ , type=UpperCamelCase__ ) expected.add_argument("--ces" , nargs="+" , default=[] , type=UpperCamelCase__ ) expected.add_argument("--des" , nargs="+" , default=[] , type=UpperCamelCase__ ) A__ = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(UpperCamelCase__ ) for dataclass_type in dataclass_types: A__ = HfArgumentParser(UpperCamelCase__ ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) A__ = parser.parse_args([] ) self.assertEqual(UpperCamelCase__ , Namespace(foo=UpperCamelCase__ , bar=UpperCamelCase__ , baz=UpperCamelCase__ , ces=[] , des=[] ) ) A__ = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split() ) self.assertEqual(UpperCamelCase__ , Namespace(foo=12 , bar=3.14 , baz="42" , ces=["a", "b", "c"] , des=[1, 2, 3] ) ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = argparse.ArgumentParser() expected.add_argument("--required_list" , nargs="+" , type=UpperCamelCase__ , required=UpperCamelCase__ ) expected.add_argument("--required_str" , type=UpperCamelCase__ , required=UpperCamelCase__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=UpperCamelCase__ , ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = argparse.ArgumentParser() expected.add_argument("--foo" , type=UpperCamelCase__ , required=UpperCamelCase__ ) expected.add_argument( "--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=UpperCamelCase__ , ) expected.add_argument("--opt" , type=UpperCamelCase__ , default=UpperCamelCase__ ) expected.add_argument("--baz" , default="toto" , type=UpperCamelCase__ , help="help message" ) expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=UpperCamelCase__ ) self.argparsersEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } A__ = parser.parse_dict(UpperCamelCase__ )[0] A__ = BasicExample(**UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, "extra": 42, } self.assertRaises(UpperCamelCase__ , parser.parse_dict , UpperCamelCase__ , allow_extra_keys=UpperCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: A__ = os.path.join(UpperCamelCase__ , "temp_json" ) os.mkdir(UpperCamelCase__ ) with open(temp_local_path + ".json" , "w+" ) as f: json.dump(UpperCamelCase__ , UpperCamelCase__ ) A__ = parser.parse_yaml_file(Path(temp_local_path + ".json" ) )[0] A__ = BasicExample(**UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) A__ = { "foo": 12, "bar": 3.14, "baz": "42", "flag": True, } with tempfile.TemporaryDirectory() as tmp_dir: A__ = os.path.join(UpperCamelCase__ , "temp_yaml" ) os.mkdir(UpperCamelCase__ ) with open(temp_local_path + ".yaml" , "w+" ) as f: yaml.dump(UpperCamelCase__ , UpperCamelCase__ ) A__ = parser.parse_yaml_file(Path(temp_local_path + ".yaml" ) )[0] A__ = BasicExample(**UpperCamelCase__ ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowercase_ ( self ): '''simple docstring''' A__ = HfArgumentParser(UpperCamelCase__ ) self.assertIsNotNone(UpperCamelCase__ )
261
"""simple docstring""" # Lint as: python3 import itertools import os import re __UpperCAmelCase =re.compile(r"""([A-Z]+)([A-Z][a-z])""") __UpperCAmelCase =re.compile(r"""([a-z\d])([A-Z])""") __UpperCAmelCase =re.compile(r"""(?<!_)_(?!_)""") __UpperCAmelCase =re.compile(r"""(_{2,})""") __UpperCAmelCase =r"""^\w+(\.\w+)*$""" __UpperCAmelCase =r"""<>:/\|?*""" def __a ( A ) -> Tuple: '''simple docstring''' A__ = _uppercase_uppercase_re.sub(R"\1_\2" , A ) A__ = _lowercase_uppercase_re.sub(R"\1_\2" , A ) return name.lower() def __a ( A ) -> int: '''simple docstring''' A__ = _single_underscore_re.split(A ) A__ = [_multiple_underscores_re.split(A ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(A ) if n != "" ) def __a ( A ) -> Optional[Any]: '''simple docstring''' if os.path.basename(A ) != name: raise ValueError(f"""Should be a dataset name, not a path: {name}""" ) return camelcase_to_snakecase(A ) def __a ( A , A ) -> Optional[int]: '''simple docstring''' if os.path.basename(A ) != name: raise ValueError(f"""Should be a dataset name, not a path: {name}""" ) if not re.match(_split_re , A ): raise ValueError(f"""Split name should match '{_split_re}'' but got '{split}'.""" ) return f"""{filename_prefix_for_name(A )}-{split}""" def __a ( A , A , A , A=None ) -> List[Any]: '''simple docstring''' A__ = filename_prefix_for_split(A , A ) if filetype_suffix: prefix += f""".{filetype_suffix}""" A__ = os.path.join(A , A ) return f"""{filepath}*""" def __a ( A , A , A , A=None , A=None ) -> List[Any]: '''simple docstring''' A__ = filename_prefix_for_split(A , A ) A__ = os.path.join(A , A ) if shard_lengths: A__ = len(A ) A__ = [f"""{prefix}-{shard_id:05d}-of-{num_shards:05d}""" for shard_id in range(A )] if filetype_suffix: A__ = [filename + f""".{filetype_suffix}""" for filename in filenames] return filenames else: A__ = prefix if filetype_suffix: filename += f""".{filetype_suffix}""" return [filename]
261
1
"""simple docstring""" __lowerCAmelCase : Optional[Any] = [ '''DownloadConfig''', '''DownloadManager''', '''DownloadMode''', '''StreamingDownloadManager''', ] from .download_config import DownloadConfig from .download_manager import DownloadManager, DownloadMode from .streaming_download_manager import StreamingDownloadManager
58
'''simple docstring''' from sklearn.metrics import mean_squared_error import datasets _lowercase = """\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ _lowercase = """\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. """ _lowercase = """ Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. \"raw_values\" : Returns a full set of errors in case of multioutput input. \"uniform_average\" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric(\"mse\") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {'mse': 0.6123724356957945} If you're using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {'mse': array([0.41666667, 1. ])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): '''simple docstring''' def _lowercase ( self ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html""" ] , ) def _lowercase ( self ): """simple docstring""" if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("""float""" ) ), "references": datasets.Sequence(datasets.Value("""float""" ) ), } else: return { "predictions": datasets.Value("""float""" ), "references": datasets.Value("""float""" ), } def _lowercase ( self , _lowercase , _lowercase , _lowercase=None , _lowercase="uniform_average" , _lowercase=True ): """simple docstring""" _lowerCAmelCase = mean_squared_error( _lowercase , _lowercase , sample_weight=_lowercase , multioutput=_lowercase , squared=_lowercase ) return {"mse": mse}
5
0
from cva import destroyAllWindows, imread, imshow, waitKey def __lowercase ( _SCREAMING_SNAKE_CASE ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE, SCREAMING_SNAKE_CASE = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(__snake_case ): for j in range(__snake_case ): SCREAMING_SNAKE_CASE = [2_55, 2_55, 2_55] - img[i][j] return img if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE_ = imread("""image_data/lena.jpg""", 1) # convert to its negative SCREAMING_SNAKE_CASE_ = convert_to_negative(img) # show result image imshow("""negative of original image""", img) waitKey(0) destroyAllWindows()
707
import inspect import re from hashlib import shaaaa from typing import Dict, List from .arrow import arrow from .audiofolder import audiofolder from .csv import csv from .imagefolder import imagefolder from .json import json from .pandas import pandas from .parquet import parquet from .sql import sql # noqa F401 from .text import text def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = [] for line in lines: SCREAMING_SNAKE_CASE = re.sub(r"""#.*""" , """""" , _SCREAMING_SNAKE_CASE ) # remove comments if line: filtered_lines.append(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE = """\n""".join(_SCREAMING_SNAKE_CASE ) # Make a hash from all this code SCREAMING_SNAKE_CASE = full_str.encode("""utf-8""" ) return shaaaa(_SCREAMING_SNAKE_CASE ).hexdigest() # get importable module names and hash for caching SCREAMING_SNAKE_CASE_ = { """csv""": (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())), """json""": (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())), """pandas""": (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())), """parquet""": (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())), """arrow""": (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())), """text""": (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())), """imagefolder""": (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())), """audiofolder""": (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())), } # Used to infer the module to use based on the data files extensions SCREAMING_SNAKE_CASE_ = { """.csv""": ("""csv""", {}), """.tsv""": ("""csv""", {"""sep""": """\t"""}), """.json""": ("""json""", {}), """.jsonl""": ("""json""", {}), """.parquet""": ("""parquet""", {}), """.arrow""": ("""arrow""", {}), """.txt""": ("""text""", {}), } _EXTENSION_TO_MODULE.update({ext: ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("""imagefolder""", {}) for ext in imagefolder.ImageFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext: ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) _EXTENSION_TO_MODULE.update({ext.upper(): ("""audiofolder""", {}) for ext in audiofolder.AudioFolder.EXTENSIONS}) SCREAMING_SNAKE_CASE_ = {"""imagefolder""", """audiofolder"""} # Used to filter data files based on extensions given a module name SCREAMING_SNAKE_CASE_ = {} for _ext, (_module, _) in _EXTENSION_TO_MODULE.items(): _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext) _MODULE_TO_EXTENSIONS["imagefolder"].append(""".zip""") _MODULE_TO_EXTENSIONS["audiofolder"].append(""".zip""")
116
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __snake_case : List[str] ={ 'configuration_xlm_roberta_xl': [ 'XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMRobertaXLConfig', 'XLMRobertaXLOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case : List[Any] =[ 'XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST', 'XLMRobertaXLForCausalLM', 'XLMRobertaXLForMaskedLM', 'XLMRobertaXLForMultipleChoice', 'XLMRobertaXLForQuestionAnswering', 'XLMRobertaXLForSequenceClassification', 'XLMRobertaXLForTokenClassification', 'XLMRobertaXLModel', 'XLMRobertaXLPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys __snake_case : int =_LazyModule(__name__, globals()['__file__'], _import_structure)
647
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class lowerCamelCase__ : '''simple docstring''' snake_case_ =None snake_case_ =False snake_case_ =False snake_case_ =False snake_case_ =None snake_case_ =None snake_case_ =False snake_case_ =False snake_case_ =False snake_case_ =True snake_case_ =None snake_case_ =1 snake_case_ =None snake_case_ =False snake_case_ =None snake_case_ =None def lowerCAmelCase__ (self ) -> "DownloadConfig": """simple docstring""" return self.__class__(**{k: copy.deepcopy(__lowerCamelCase ) for k, v in self.__dict__.items()} )
647
1
"""simple docstring""" __lowerCAmelCase : Optional[Any] = { "A": ".-", "B": "-...", "C": "-.-.", "D": "-..", "E": ".", "F": "..-.", "G": "--.", "H": "....", "I": "..", "J": ".---", "K": "-.-", "L": ".-..", "M": "--", "N": "-.", "O": "---", "P": ".--.", "Q": "--.-", "R": ".-.", "S": "...", "T": "-", "U": "..-", "V": "...-", "W": ".--", "X": "-..-", "Y": "-.--", "Z": "--..", "1": ".----", "2": "..---", "3": "...--", "4": "....-", "5": ".....", "6": "-....", "7": "--...", "8": "---..", "9": "----.", "0": "-----", "&": ".-...", "@": ".--.-.", ":": "---...", ",": "--..--", ".": ".-.-.-", "'": ".----.", "\"": ".-..-.", "?": "..--..", "/": "-..-.", "=": "-...-", "+": ".-.-.", "-": "-....-", "(": "-.--.", ")": "-.--.-", "!": "-.-.--", " ": "/" } # Exclamation mark is not in ITU-R recommendation # fmt: on __lowerCAmelCase : Dict = {value: key for key, value in MORSE_CODE_DICT.items()} def _UpperCAmelCase ( lowerCamelCase__ ): """simple docstring""" return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def _UpperCAmelCase ( lowerCamelCase__ ): """simple docstring""" return "".join(REVERSE_DICT[char] for char in message.split() ) def _UpperCAmelCase ( ): """simple docstring""" lowerCAmelCase__ = """Morse code here!""" print(lowerCamelCase__ ) lowerCAmelCase__ = encrypt(lowerCamelCase__ ) print(lowerCamelCase__ ) lowerCAmelCase__ = decrypt(lowerCamelCase__ ) print(lowerCamelCase__ ) if __name__ == "__main__": main()
674
"""simple docstring""" def _UpperCAmelCase ( lowerCamelCase__ = 50 ): """simple docstring""" lowerCAmelCase__ = [[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() = }")
674
1
import numpy as np def __lowerCAmelCase( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 1e-12 , _SCREAMING_SNAKE_CASE = 100 , ) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(_SCREAMING_SNAKE_CASE )[0] == np.shape(_SCREAMING_SNAKE_CASE )[1] # Ensure proper dimensionality. assert np.shape(_SCREAMING_SNAKE_CASE )[0] == np.shape(_SCREAMING_SNAKE_CASE )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(_SCREAMING_SNAKE_CASE ) == np.iscomplexobj(_SCREAMING_SNAKE_CASE ) _A = np.iscomplexobj(_SCREAMING_SNAKE_CASE ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(_SCREAMING_SNAKE_CASE , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. _A = False _A = 0 _A = 0 _A = 1e12 while not convergence: # Multiple matrix by the vector. _A = np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Normalize the resulting output vector. _A = w / np.linalg.norm(_SCREAMING_SNAKE_CASE ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) _A = vector.conj().T if is_complex else vector.T _A = np.dot(_SCREAMING_SNAKE_CASE , np.dot(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # Check convergence. _A = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: _A = True _A = lambda_ if is_complex: _A = np.real(lambda_ ) return lambda_, vector def __lowerCAmelCase( ) -> None: """simple docstring""" _A = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) _A = np.array([41, 4, 20] ) _A = real_input_matrix.astype(np.complexaaa ) _A = np.triu(1j * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T _A = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": _A = real_input_matrix _A = real_vector elif problem_type == "complex": _A = complex_input_matrix _A = complex_vector # Our implementation. _A, _A = power_iteration(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). _A, _A = np.linalg.eigh(_SCREAMING_SNAKE_CASE ) # Last eigenvalue is the maximum one. _A = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. _A = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1e-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(_SCREAMING_SNAKE_CASE ) - np.abs(_SCREAMING_SNAKE_CASE ) ) <= 1e-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
27
"""simple docstring""" import numpy # List of input, output pairs SCREAMING_SNAKE_CASE__ : Optional[Any] =( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) SCREAMING_SNAKE_CASE__ : str =(((515, 22, 13), 555), ((61, 35, 49), 150)) SCREAMING_SNAKE_CASE__ : int =[2, 4, 1, 5] SCREAMING_SNAKE_CASE__ : Any =len(train_data) SCREAMING_SNAKE_CASE__ : List[Any] =0.009 def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_="train" ) ->List[str]: return calculate_hypothesis_value(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) - output( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->Tuple: _lowerCamelCase : int = 0 for i in range(len(SCREAMING_SNAKE_CASE_ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ->Union[str, Any]: if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ->Optional[Any]: if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=m ) ->List[str]: _lowerCamelCase : Tuple = 0 for i in range(SCREAMING_SNAKE_CASE_ ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE_ ) else: summation_value += _error(SCREAMING_SNAKE_CASE_ ) * train_data[i][0][index] return summation_value def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->List[str]: _lowerCamelCase : Optional[Any] = summation_of_cost_derivative(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) / m return cost_derivative_value def UpperCamelCase ( ) ->Optional[Any]: global parameter_vector # Tune these values to set a tolerance value for predicted output _lowerCamelCase : Dict = 0.000002 _lowerCamelCase : List[str] = 0 _lowerCamelCase : Union[str, Any] = 0 while True: j += 1 _lowerCamelCase : str = [0, 0, 0, 0] for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) ): _lowerCamelCase : Optional[int] = get_cost_derivative(i - 1 ) _lowerCamelCase : Optional[Any] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ , rtol=SCREAMING_SNAKE_CASE_ , ): break _lowerCamelCase : List[str] = temp_parameter_vector print(('''Number of iterations:''', j) ) def UpperCamelCase ( ) ->Optional[Any]: for i in range(len(SCREAMING_SNAKE_CASE_ ) ): print(('''Actual output value:''', output(SCREAMING_SNAKE_CASE_ , '''test''' )) ) print(('''Hypothesis output:''', calculate_hypothesis_value(SCREAMING_SNAKE_CASE_ , '''test''' )) ) if __name__ == "__main__": run_gradient_descent() print('\nTesting gradient descent for a linear hypothesis function.\n') test_gradient_descent()
434
0
"""simple docstring""" import sys A = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def lowerCAmelCase__ ( lowerCamelCase__ = N ) -> int: A = -sys.maxsize - 1 for i in range(len(lowerCamelCase__ ) - 12 ): A = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: A = product return largest_product if __name__ == "__main__": print(F'{solution() = }')
109
"""simple docstring""" import re def lowerCAmelCase__ ( lowerCamelCase__ ) -> list: return [char.split() for char in re.split(R'[^ a-z A-Z 0-9 \s]' , str_ )] def lowerCAmelCase__ ( lowerCamelCase__ ) -> str: A = split_input(str_ ) return "".join( [''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCAmelCase__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: try: A = split_input(lowerCamelCase__ ) if upper: A = ''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: A = ''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCAmelCase__ ( lowerCamelCase__ ) -> str: return to_simple_case(lowerCamelCase__ ) def lowerCAmelCase__ ( lowerCamelCase__ ) -> str: try: A = to_simple_case(lowerCamelCase__ ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCAmelCase__ ( lowerCamelCase__ , lowerCamelCase__ ) -> str: return to_complex_case(lowerCamelCase__ , lowerCamelCase__ , '_' ) def lowerCAmelCase__ ( lowerCamelCase__ , lowerCamelCase__ ) -> str: return to_complex_case(lowerCamelCase__ , lowerCamelCase__ , '-' ) if __name__ == "__main__": __import__('doctest').testmod()
109
1
def SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ ): UpperCamelCase__ : Optional[Any] = '''''' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ ): UpperCamelCase__ : Tuple = [chr(i + 6_5 ) for i in range(2_6 )] # Remove duplicate characters from key UpperCamelCase__ : str = remove_duplicates(key.upper() ) UpperCamelCase__ : Any = len(UpperCamelCase__ ) # First fill cipher with key characters UpperCamelCase__ : Optional[int] = {alphabet[i]: char for i, char in enumerate(UpperCamelCase__ )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(UpperCamelCase__ ) , 2_6 ): UpperCamelCase__ : List[Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 UpperCamelCase__ : List[Any] = alphabet[i - offset] UpperCamelCase__ : List[Any] = char return cipher_alphabet def SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ , UpperCamelCase__ ): return "".join(cipher_map.get(UpperCamelCase__ , UpperCamelCase__ ) for ch in message.upper() ) def SCREAMING_SNAKE_CASE_ ( UpperCamelCase__ , UpperCamelCase__ ): UpperCamelCase__ : Dict = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(UpperCamelCase__ , UpperCamelCase__ ) for ch in message.upper() ) def SCREAMING_SNAKE_CASE_ ( ): UpperCamelCase__ : Any = input('''Enter message to encode or decode: ''' ).strip() UpperCamelCase__ : Tuple = input('''Enter keyword: ''' ).strip() UpperCamelCase__ : List[str] = input('''Encipher or decipher? E/D:''' ).strip()[0].lower() try: UpperCamelCase__ : Optional[int] = {'''e''': encipher, '''d''': decipher}[option] except KeyError: raise KeyError('''invalid input option''' ) UpperCamelCase__ : Any = create_cipher_map(UpperCamelCase__ ) print(func(UpperCamelCase__ , UpperCamelCase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
285
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase =logging.get_logger(__name__) lowerCamelCase ={ "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/config.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/config.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json" ), "distilbert-base-uncased-finetuned-sst-2-english": ( "https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json" ), } class _lowerCamelCase ( UpperCamelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = '''distilbert''' SCREAMING_SNAKE_CASE_ = { '''hidden_size''': '''dim''', '''num_attention_heads''': '''n_heads''', '''num_hidden_layers''': '''n_layers''', } def __init__( self , __SCREAMING_SNAKE_CASE=3_0_5_2_2 , __SCREAMING_SNAKE_CASE=5_1_2 , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=6 , __SCREAMING_SNAKE_CASE=1_2 , __SCREAMING_SNAKE_CASE=7_6_8 , __SCREAMING_SNAKE_CASE=4 * 7_6_8 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.2 , __SCREAMING_SNAKE_CASE=0 , **__SCREAMING_SNAKE_CASE , ) -> Optional[Any]: """simple docstring""" UpperCamelCase__ : List[Any] = vocab_size UpperCamelCase__ : Dict = max_position_embeddings UpperCamelCase__ : Any = sinusoidal_pos_embds UpperCamelCase__ : Dict = n_layers UpperCamelCase__ : List[Any] = n_heads UpperCamelCase__ : Dict = dim UpperCamelCase__ : Dict = hidden_dim UpperCamelCase__ : Optional[int] = dropout UpperCamelCase__ : Optional[Any] = attention_dropout UpperCamelCase__ : Tuple = activation UpperCamelCase__ : Optional[int] = initializer_range UpperCamelCase__ : Optional[int] = qa_dropout UpperCamelCase__ : str = seq_classif_dropout super().__init__(**__SCREAMING_SNAKE_CASE , pad_token_id=__SCREAMING_SNAKE_CASE ) class _lowerCamelCase ( UpperCamelCase_ ): """simple docstring""" @property def __SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": UpperCamelCase__ : Union[str, Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCamelCase__ : int = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
285
1
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch __A : List[Any] = logging.get_logger(__name__) @add_end_docstrings( lowerCAmelCase__ , r"\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n " , ) class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__): def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> np.ndarray: if self.framework == "tf": lowerCamelCase_ =tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": lowerCamelCase_ =torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_SCREAMING_SNAKE_CASE ) else: raise ValueError("""Unsupported framework""" ) return masked_index def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> np.ndarray: lowerCamelCase_ =self.get_masked_index(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =np.prod(masked_index.shape ) if numel < 1: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , f'No mask_token ({self.tokenizer.mask_token}) found on the input' , ) def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(_SCREAMING_SNAKE_CASE ) def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE )-> Dict[str, GenericTensor]: if return_tensors is None: lowerCamelCase_ =self.framework lowerCamelCase_ =self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) self.ensure_exactly_one_mask_token(_SCREAMING_SNAKE_CASE ) return model_inputs def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]: lowerCamelCase_ =self.model(**_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =model_inputs["""input_ids"""] return model_outputs def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=None )-> Tuple: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: lowerCamelCase_ =target_ids.shape[0] lowerCamelCase_ =model_outputs["""input_ids"""][0] lowerCamelCase_ =model_outputs["""logits"""] if self.framework == "tf": lowerCamelCase_ =tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] lowerCamelCase_ =outputs.numpy() lowerCamelCase_ =outputs[0, masked_index, :] lowerCamelCase_ =stable_softmax(_SCREAMING_SNAKE_CASE , axis=-1 ) if target_ids is not None: lowerCamelCase_ =tf.gather_nd(tf.squeeze(_SCREAMING_SNAKE_CASE , 0 ) , target_ids.reshape(-1 , 1 ) ) lowerCamelCase_ =tf.expand_dims(_SCREAMING_SNAKE_CASE , 0 ) lowerCamelCase_ =tf.math.top_k(_SCREAMING_SNAKE_CASE , k=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ , lowerCamelCase_ =topk.values.numpy(), topk.indices.numpy() else: lowerCamelCase_ =torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=_SCREAMING_SNAKE_CASE ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample lowerCamelCase_ =outputs[0, masked_index, :] lowerCamelCase_ =logits.softmax(dim=-1 ) if target_ids is not None: lowerCamelCase_ =probs[..., target_ids] lowerCamelCase_ , lowerCamelCase_ =probs.topk(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =[] lowerCamelCase_ =values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): lowerCamelCase_ =[] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place lowerCamelCase_ =input_ids.numpy().copy() if target_ids is not None: lowerCamelCase_ =target_ids[p].tolist() lowerCamelCase_ =p # Filter padding out: lowerCamelCase_ =tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back lowerCamelCase_ =self.tokenizer.decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE ) lowerCamelCase_ ={"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p] ), """sequence""": sequence} row.append(_SCREAMING_SNAKE_CASE ) result.append(_SCREAMING_SNAKE_CASE ) if single_mask: return result[0] return result def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None )-> int: if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): lowerCamelCase_ =[targets] try: lowerCamelCase_ =self.tokenizer.get_vocab() except Exception: lowerCamelCase_ ={} lowerCamelCase_ =[] for target in targets: lowerCamelCase_ =vocab.get(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if id_ is None: lowerCamelCase_ =self.tokenizer( _SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , return_token_type_ids=_SCREAMING_SNAKE_CASE , max_length=1 , truncation=_SCREAMING_SNAKE_CASE , )["""input_ids"""] if len(_SCREAMING_SNAKE_CASE ) == 0: logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' """We cannot replace it with anything meaningful, ignoring it""" ) continue lowerCamelCase_ =input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( f'The specified target token `{target}` does not exist in the model vocabulary. ' f'Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.' ) target_ids.append(id_ ) lowerCamelCase_ =list(set(_SCREAMING_SNAKE_CASE ) ) if len(_SCREAMING_SNAKE_CASE ) == 0: raise ValueError("""At least one target must be provided when passed.""" ) lowerCamelCase_ =np.array(_SCREAMING_SNAKE_CASE ) return target_ids def _snake_case ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None )-> int: lowerCamelCase_ ={} if targets is not None: lowerCamelCase_ =self.get_target_ids(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) lowerCamelCase_ =target_ids if top_k is not None: lowerCamelCase_ =top_k if self.tokenizer.mask_token_id is None: raise PipelineException( """fill-mask""" , self.model.base_model_prefix , """The tokenizer does not define a `mask_token`.""" ) return {}, {}, postprocess_params def __call__( self , _SCREAMING_SNAKE_CASE , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> str: lowerCamelCase_ =super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) == 1: return outputs[0] return outputs
75
def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[[] for _ in range(_A )] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1 or len(_A ) <= key: return input_string for position, character in enumerate(_A ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(_A ) lowerCamelCase_ =["""""".join(_A ) for row in temp_grid] lowerCamelCase_ ="""""".join(_A ) return output_string def __UpperCamelCase ( _A : str , _A : int ) ->str: """simple docstring""" lowerCamelCase_ =[] lowerCamelCase_ =key - 1 if key <= 0: raise ValueError("""Height of grid can't be 0 or negative""" ) if key == 1: return input_string lowerCamelCase_ =[[] for _ in range(_A )] # generates template for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("""*""" ) lowerCamelCase_ =0 for row in temp_grid: # fills in the characters lowerCamelCase_ =input_string[counter : counter + len(_A )] grid.append(list(_A ) ) counter += len(_A ) lowerCamelCase_ ="""""" # reads as zigzag for position in range(len(_A ) ): lowerCamelCase_ =position % (lowest * 2) # puts it in bounds lowerCamelCase_ =min(_A , lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __UpperCamelCase ( _A : str ) ->dict[int, str]: """simple docstring""" lowerCamelCase_ ={} for key_guess in range(1 , len(_A ) ): # tries every key lowerCamelCase_ =decrypt(_A , _A ) return results if __name__ == "__main__": import doctest doctest.testmod()
75
1
from __future__ import annotations def lowerCAmelCase__ ( a__ , a__ ) ->bool: '''simple docstring''' _UpperCamelCase = get_failure_array(a__ ) # 2) Step through text searching for pattern _UpperCamelCase , _UpperCamelCase = 0, 0 # index into text, pattern while i < len(a__ ): if pattern[j] == text[i]: if j == (len(a__ ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: _UpperCamelCase = failure[j - 1] continue i += 1 return False def lowerCAmelCase__ ( a__ ) ->list[int]: '''simple docstring''' _UpperCamelCase = [0] _UpperCamelCase = 0 _UpperCamelCase = 1 while j < len(a__ ): if pattern[i] == pattern[j]: i += 1 elif i > 0: _UpperCamelCase = failure[i - 1] continue j += 1 failure.append(a__ ) return failure if __name__ == "__main__": # Test 1) lowerCamelCase__ = '''abc1abc12''' lowerCamelCase__ = '''alskfjaldsabc1abc1abc12k23adsfabcabc''' lowerCamelCase__ = '''alskfjaldsk23adsfabcabc''' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) lowerCamelCase__ = '''ABABX''' lowerCamelCase__ = '''ABABZABABYABABX''' assert kmp(pattern, text) # Test 3) lowerCamelCase__ = '''AAAB''' lowerCamelCase__ = '''ABAAAAAB''' assert kmp(pattern, text) # Test 4) lowerCamelCase__ = '''abcdabcy''' lowerCamelCase__ = '''abcxabcdabxabcdabcdabcy''' assert kmp(pattern, text) # Test 5) lowerCamelCase__ = '''aabaabaaa''' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
547
import unittest from transformers import BigBirdConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any] , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any]=2 , lowercase_ : Dict=56 , lowercase_ : str=True , lowercase_ : Optional[Any]=True , lowercase_ : List[Any]=True , lowercase_ : Union[str, Any]=True , lowercase_ : Any=99 , lowercase_ : Optional[int]=32 , lowercase_ : Tuple=2 , lowercase_ : int=2 , lowercase_ : List[str]=7 , lowercase_ : Any="gelu_new" , lowercase_ : List[str]=0.1 , lowercase_ : str=0.1 , lowercase_ : List[Any]=512 , lowercase_ : List[str]=16 , lowercase_ : Optional[int]=2 , lowercase_ : Union[str, Any]=0.02 , lowercase_ : Union[str, Any]=4 , lowercase_ : Union[str, Any]="block_sparse" , lowercase_ : Tuple=True , lowercase_ : Dict=False , lowercase_ : Dict=2 , lowercase_ : Dict=3 , ) -> List[str]: """simple docstring""" _UpperCamelCase = parent _UpperCamelCase = batch_size _UpperCamelCase = seq_length _UpperCamelCase = is_training _UpperCamelCase = use_attention_mask _UpperCamelCase = use_token_type_ids _UpperCamelCase = use_labels _UpperCamelCase = vocab_size _UpperCamelCase = hidden_size _UpperCamelCase = num_hidden_layers _UpperCamelCase = num_attention_heads _UpperCamelCase = intermediate_size _UpperCamelCase = hidden_act _UpperCamelCase = hidden_dropout_prob _UpperCamelCase = attention_probs_dropout_prob _UpperCamelCase = max_position_embeddings _UpperCamelCase = type_vocab_size _UpperCamelCase = type_sequence_label_size _UpperCamelCase = initializer_range _UpperCamelCase = num_choices _UpperCamelCase = rescale_embeddings _UpperCamelCase = attention_type _UpperCamelCase = use_bias _UpperCamelCase = block_size _UpperCamelCase = num_random_blocks def __UpperCAmelCase ( self : List[Any]) -> Dict: """simple docstring""" _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) _UpperCamelCase = None if self.use_attention_mask: _UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length]) _UpperCamelCase = None if self.use_token_type_ids: _UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) _UpperCamelCase = BigBirdConfig( 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=lowercase_ , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def __UpperCAmelCase ( self : Optional[Any]) -> Optional[Any]: """simple docstring""" _UpperCamelCase = self.prepare_config_and_inputs() _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = config_and_inputs _UpperCamelCase = { "input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask, } return config, inputs_dict @require_flax class _UpperCAmelCase ( lowerCAmelCase, unittest.TestCase ): '''simple docstring''' __A = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) __A = False __A = False def __UpperCAmelCase ( self : Optional[int]) -> Optional[Any]: """simple docstring""" _UpperCamelCase = FlaxBigBirdModelTester(self) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : Union[str, Any]) -> List[str]: """simple docstring""" super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : Any) -> int: """simple docstring""" super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : List[Any]) -> Union[str, Any]: """simple docstring""" super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : str) -> Union[str, Any]: """simple docstring""" super().test_hidden_states_output() @slow def __UpperCAmelCase ( self : Tuple) -> Optional[int]: """simple docstring""" for model_class_name in self.all_model_classes: _UpperCamelCase = model_class_name.from_pretrained("google/bigbird-roberta-base") self.assertIsNotNone(lowercase_) def __UpperCAmelCase ( self : Tuple) -> str: """simple docstring""" if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : Tuple) -> Dict: """simple docstring""" _UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__): _UpperCamelCase = self._prepare_for_class(lowercase_ , lowercase_) _UpperCamelCase = model_class(lowercase_) @jax.jit def model_jitted(lowercase_ : Dict , lowercase_ : List[Any]=None , **lowercase_ : Tuple): return model(input_ids=lowercase_ , attention_mask=lowercase_ , **lowercase_) with self.subTest("JIT Enabled"): _UpperCamelCase = model_jitted(**lowercase_).to_tuple() with self.subTest("JIT Disabled"): with jax.disable_jit(): _UpperCamelCase = model_jitted(**lowercase_).to_tuple() self.assertEqual(len(lowercase_) , len(lowercase_)) for jitted_output, output in zip(lowercase_ , lowercase_): self.assertEqual(jitted_output.shape , output.shape) def __UpperCAmelCase ( self : Any , lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : str=1e-5 , lowercase_ : int="outputs" , lowercase_ : List[str]=None) -> Tuple: """simple docstring""" if name.startswith("outputs.attentions"): return else: super().check_pt_flax_outputs(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_)
547
1
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) lowerCAmelCase : str = { """EleutherAI/gpt-j-6B""": """https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json""", # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" __magic_name__ = "gptj" __magic_name__ = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , snake_case__=5_0400 , snake_case__=2048 , snake_case__=4096 , snake_case__=28 , snake_case__=16 , snake_case__=64 , snake_case__=None , snake_case__="gelu_new" , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=1E-5 , snake_case__=0.02 , snake_case__=True , snake_case__=5_0256 , snake_case__=5_0256 , snake_case__=False , **snake_case__ , ): '''simple docstring''' _lowerCAmelCase : int = vocab_size _lowerCAmelCase : Optional[int] = n_positions _lowerCAmelCase : Optional[int] = n_embd _lowerCAmelCase : Optional[int] = n_layer _lowerCAmelCase : str = n_head _lowerCAmelCase : Tuple = n_inner _lowerCAmelCase : Tuple = rotary_dim _lowerCAmelCase : Optional[int] = activation_function _lowerCAmelCase : Any = resid_pdrop _lowerCAmelCase : List[str] = embd_pdrop _lowerCAmelCase : int = attn_pdrop _lowerCAmelCase : Any = layer_norm_epsilon _lowerCAmelCase : Optional[int] = initializer_range _lowerCAmelCase : List[str] = use_cache _lowerCAmelCase : Dict = bos_token_id _lowerCAmelCase : Any = eos_token_id super().__init__( bos_token_id=snake_case__ , eos_token_id=snake_case__ , tie_word_embeddings=snake_case__ , **snake_case__ ) class UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self , snake_case__ , snake_case__ = "default" , snake_case__ = None , snake_case__ = False , ): '''simple docstring''' super().__init__(snake_case__ , task=snake_case__ , patching_specs=snake_case__ , use_past=snake_case__ ) if not getattr(self._config , 'pad_token_id' , snake_case__ ): # TODO: how to do that better? _lowerCAmelCase : Any = 0 @property def a ( self ): '''simple docstring''' _lowerCAmelCase : str = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(snake_case__ , direction='inputs' ) _lowerCAmelCase : int = {0: 'batch', 1: 'past_sequence + sequence'} else: _lowerCAmelCase : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def a ( self ): '''simple docstring''' return self._config.n_layer @property def a ( self ): '''simple docstring''' return self._config.n_head def a ( self , snake_case__ , snake_case__ = -1 , snake_case__ = -1 , snake_case__ = False , snake_case__ = None , ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = super(snake_case__ , self ).generate_dummy_inputs( snake_case__ , batch_size=snake_case__ , seq_length=snake_case__ , is_pair=snake_case__ , framework=snake_case__ ) # We need to order the input in the way they appears in the forward() _lowerCAmelCase : Any = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch _lowerCAmelCase : Optional[Any] = common_inputs['input_ids'].shape # Not using the same length for past_key_values _lowerCAmelCase : Any = seqlen + 2 _lowerCAmelCase : Optional[int] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _lowerCAmelCase : Tuple = [ (torch.zeros(snake_case__ ), torch.zeros(snake_case__ )) for _ in range(self.num_layers ) ] _lowerCAmelCase : Tuple = common_inputs['attention_mask'] if self.use_past: _lowerCAmelCase : Any = ordered_inputs['attention_mask'].dtype _lowerCAmelCase : Union[str, Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(snake_case__ , snake_case__ , dtype=snake_case__ )] , dim=1 ) return ordered_inputs @property def a ( self ): '''simple docstring''' return 13
714
'''simple docstring''' from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) lowerCAmelCase : str = { """EleutherAI/gpt-j-6B""": """https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json""", # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" __magic_name__ = "gptj" __magic_name__ = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , snake_case__=5_0400 , snake_case__=2048 , snake_case__=4096 , snake_case__=28 , snake_case__=16 , snake_case__=64 , snake_case__=None , snake_case__="gelu_new" , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.0 , snake_case__=1E-5 , snake_case__=0.02 , snake_case__=True , snake_case__=5_0256 , snake_case__=5_0256 , snake_case__=False , **snake_case__ , ): '''simple docstring''' _lowerCAmelCase : int = vocab_size _lowerCAmelCase : Optional[int] = n_positions _lowerCAmelCase : Optional[int] = n_embd _lowerCAmelCase : Optional[int] = n_layer _lowerCAmelCase : str = n_head _lowerCAmelCase : Tuple = n_inner _lowerCAmelCase : Tuple = rotary_dim _lowerCAmelCase : Optional[int] = activation_function _lowerCAmelCase : Any = resid_pdrop _lowerCAmelCase : List[str] = embd_pdrop _lowerCAmelCase : int = attn_pdrop _lowerCAmelCase : Any = layer_norm_epsilon _lowerCAmelCase : Optional[int] = initializer_range _lowerCAmelCase : List[str] = use_cache _lowerCAmelCase : Dict = bos_token_id _lowerCAmelCase : Any = eos_token_id super().__init__( bos_token_id=snake_case__ , eos_token_id=snake_case__ , tie_word_embeddings=snake_case__ , **snake_case__ ) class UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self , snake_case__ , snake_case__ = "default" , snake_case__ = None , snake_case__ = False , ): '''simple docstring''' super().__init__(snake_case__ , task=snake_case__ , patching_specs=snake_case__ , use_past=snake_case__ ) if not getattr(self._config , 'pad_token_id' , snake_case__ ): # TODO: how to do that better? _lowerCAmelCase : Any = 0 @property def a ( self ): '''simple docstring''' _lowerCAmelCase : str = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(snake_case__ , direction='inputs' ) _lowerCAmelCase : int = {0: 'batch', 1: 'past_sequence + sequence'} else: _lowerCAmelCase : int = {0: 'batch', 1: 'sequence'} return common_inputs @property def a ( self ): '''simple docstring''' return self._config.n_layer @property def a ( self ): '''simple docstring''' return self._config.n_head def a ( self , snake_case__ , snake_case__ = -1 , snake_case__ = -1 , snake_case__ = False , snake_case__ = None , ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = super(snake_case__ , self ).generate_dummy_inputs( snake_case__ , batch_size=snake_case__ , seq_length=snake_case__ , is_pair=snake_case__ , framework=snake_case__ ) # We need to order the input in the way they appears in the forward() _lowerCAmelCase : Any = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = common_inputs['input_ids'].shape # Not using the same length for past_key_values _lowerCAmelCase : Any = seqlen + 2 _lowerCAmelCase : Optional[int] = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _lowerCAmelCase : Tuple = [ (torch.zeros(snake_case__ ), torch.zeros(snake_case__ )) for _ in range(self.num_layers ) ] _lowerCAmelCase : Tuple = common_inputs['attention_mask'] if self.use_past: _lowerCAmelCase : Any = ordered_inputs['attention_mask'].dtype _lowerCAmelCase : Union[str, Any] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(snake_case__ , snake_case__ , dtype=snake_case__ )] , dim=1 ) return ordered_inputs @property def a ( self ): '''simple docstring''' return 13
630
0
'''simple docstring''' import re import string import numpy as np import datasets SCREAMING_SNAKE_CASE = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' SCREAMING_SNAKE_CASE = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' SCREAMING_SNAKE_CASE = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase_ ( datasets.Metric ): """simple docstring""" def A__ ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Value('''string''' , id='''sequence''' ), } ) , reference_urls=[] , ) def A__ ( self : Any , UpperCAmelCase : Optional[Any] , UpperCAmelCase : Any , UpperCAmelCase : Union[str, Any]=None , UpperCAmelCase : int=False , UpperCAmelCase : Tuple=False , UpperCAmelCase : List[str]=False , ) -> Dict: '''simple docstring''' if regexes_to_ignore is not None: for s in regexes_to_ignore: lowercase : str =np.array([re.sub(UpperCAmelCase , '''''' , UpperCAmelCase ) for x in predictions] ) lowercase : List[Any] =np.array([re.sub(UpperCAmelCase , '''''' , UpperCAmelCase ) for x in references] ) else: lowercase : int =np.asarray(UpperCAmelCase ) lowercase : str =np.asarray(UpperCAmelCase ) if ignore_case: lowercase : Optional[int] =np.char.lower(UpperCAmelCase ) lowercase : int =np.char.lower(UpperCAmelCase ) if ignore_punctuation: lowercase : str =string.punctuation.maketrans('''''' , '''''' , string.punctuation ) lowercase : int =np.char.translate(UpperCAmelCase , table=UpperCAmelCase ) lowercase : Union[str, Any] =np.char.translate(UpperCAmelCase , table=UpperCAmelCase ) if ignore_numbers: lowercase : int =string.digits.maketrans('''''' , '''''' , string.digits ) lowercase : List[Any] =np.char.translate(UpperCAmelCase , table=UpperCAmelCase ) lowercase : int =np.char.translate(UpperCAmelCase , table=UpperCAmelCase ) lowercase : List[Any] =predictions == references return {"exact_match": np.mean(UpperCAmelCase ) * 100}
94
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer __lowercase = logging.get_logger(__name__) # pylint: disable=invalid-name __lowercase = ''' Examples: ```py >>> from PIL import Image >>> import torch >>> from diffusers import DiffusionPipeline >>> from diffusers.utils import export_to_gif, load_image >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu") >>> repo = "openai/shap-e-img2img" >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16) >>> pipe = pipe.to(device) >>> guidance_scale = 3.0 >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png" >>> image = load_image(image_url).convert("RGB") >>> images = pipe( ... image, ... guidance_scale=guidance_scale, ... num_inference_steps=64, ... frame_size=256, ... ).images >>> gif_path = export_to_gif(images[0], "corgi_3d.gif") ``` ''' @dataclass class a__( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase_ : Union[PIL.Image.Image, np.ndarray] class a__( lowerCAmelCase__ ): '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): """simple docstring""" super().__init__() self.register_modules( prior=__lowerCAmelCase , image_encoder=__lowerCAmelCase , image_processor=__lowerCAmelCase , scheduler=__lowerCAmelCase , renderer=__lowerCAmelCase , ) def a_ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase): """simple docstring""" if latents is None: lowerCAmelCase = 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}") lowerCAmelCase = latents.to(__lowerCAmelCase) lowerCAmelCase = latents * scheduler.init_noise_sigma return latents def a_ ( self , __lowerCAmelCase=0): """simple docstring""" if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""") lowerCAmelCase = torch.device(f"cuda:{gpu_id}") lowerCAmelCase = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__lowerCAmelCase , __lowerCAmelCase) @property def a_ ( self): """simple docstring""" if self.device != torch.device("""meta""") or not hasattr(self.image_encoder , """_hf_hook"""): return self.device for module in self.image_encoder.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 def a_ ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ): """simple docstring""" if isinstance(__lowerCAmelCase , __lowerCAmelCase) and isinstance(image[0] , torch.Tensor): lowerCAmelCase = torch.cat(__lowerCAmelCase , axis=0) if image[0].ndim == 4 else torch.stack(__lowerCAmelCase , axis=0) if not isinstance(__lowerCAmelCase , torch.Tensor): lowerCAmelCase = self.image_processor(__lowerCAmelCase , return_tensors="""pt""").pixel_values[0].unsqueeze(0) lowerCAmelCase = image.to(dtype=self.image_encoder.dtype , device=__lowerCAmelCase) lowerCAmelCase = self.image_encoder(__lowerCAmelCase)["""last_hidden_state"""] lowerCAmelCase = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 lowerCAmelCase = image_embeds.repeat_interleave(__lowerCAmelCase , dim=0) if do_classifier_free_guidance: lowerCAmelCase = torch.zeros_like(__lowerCAmelCase) # 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 lowerCAmelCase = torch.cat([negative_image_embeds, image_embeds]) return image_embeds @torch.no_grad() @replace_example_docstring(__lowerCAmelCase) def __call__( self , __lowerCAmelCase , __lowerCAmelCase = 1 , __lowerCAmelCase = 25 , __lowerCAmelCase = None , __lowerCAmelCase = None , __lowerCAmelCase = 4.0 , __lowerCAmelCase = 64 , __lowerCAmelCase = "pil" , __lowerCAmelCase = True , ): """simple docstring""" if isinstance(__lowerCAmelCase , PIL.Image.Image): lowerCAmelCase = 1 elif isinstance(__lowerCAmelCase , torch.Tensor): lowerCAmelCase = image.shape[0] elif isinstance(__lowerCAmelCase , __lowerCAmelCase) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image)): lowerCAmelCase = len(__lowerCAmelCase) else: raise ValueError( f"`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__lowerCAmelCase)}") lowerCAmelCase = self._execution_device lowerCAmelCase = batch_size * num_images_per_prompt lowerCAmelCase = guidance_scale > 1.0 lowerCAmelCase = self._encode_image(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase) # prior self.scheduler.set_timesteps(__lowerCAmelCase , device=__lowerCAmelCase) lowerCAmelCase = self.scheduler.timesteps lowerCAmelCase = self.prior.config.num_embeddings lowerCAmelCase = self.prior.config.embedding_dim lowerCAmelCase = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim lowerCAmelCase = latents.reshape(latents.shape[0] , __lowerCAmelCase , __lowerCAmelCase) for i, t in enumerate(self.progress_bar(__lowerCAmelCase)): # expand the latents if we are doing classifier free guidance lowerCAmelCase = torch.cat([latents] * 2) if do_classifier_free_guidance else latents lowerCAmelCase = self.scheduler.scale_model_input(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = self.prior( __lowerCAmelCase , timestep=__lowerCAmelCase , proj_embedding=__lowerCAmelCase , ).predicted_image_embedding # remove the variance lowerCAmelCase , lowerCAmelCase = noise_pred.split( scaled_model_input.shape[2] , dim=2) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: lowerCAmelCase , lowerCAmelCase = noise_pred.chunk(2) lowerCAmelCase = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) lowerCAmelCase = self.scheduler.step( __lowerCAmelCase , timestep=__lowerCAmelCase , sample=__lowerCAmelCase , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=__lowerCAmelCase) lowerCAmelCase = [] for i, latent in enumerate(__lowerCAmelCase): print() lowerCAmelCase = self.renderer.decode( latent[None, :] , __lowerCAmelCase , size=__lowerCAmelCase , ray_batch_size=4096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(__lowerCAmelCase) lowerCAmelCase = torch.stack(__lowerCAmelCase) if output_type not in ["np", "pil"]: raise ValueError(f"Only the output types `pil` and `np` are supported not output_type={output_type}") lowerCAmelCase = images.cpu().numpy() if output_type == "pil": lowerCAmelCase = [self.numpy_to_pil(__lowerCAmelCase) for image in images] # Offload last model to CPU if hasattr(self , """final_offload_hook""") and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=__lowerCAmelCase)
370
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.alt_diffusion.modeling_roberta_series import ( RobertaSeriesConfig, RobertaSeriesModelWithTransformation, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase__ (lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): """simple docstring""" __UpperCamelCase : Optional[Any] = AltDiffusionPipeline __UpperCamelCase : Dict = TEXT_TO_IMAGE_PARAMS __UpperCamelCase : Union[str, Any] = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCamelCase : Tuple = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase : Any = TEXT_TO_IMAGE_IMAGE_PARAMS def lowercase ( self : Any ): torch.manual_seed(0 ) snake_case__ : int = 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.00085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=__lowerCamelCase , set_alpha_to_one=__lowerCamelCase , ) torch.manual_seed(0 ) snake_case__ : Optional[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 , ) # TODO: address the non-deterministic text encoder (fails for save-load tests) # torch.manual_seed(0) # text_encoder_config = RobertaSeriesConfig( # hidden_size=32, # project_dim=32, # intermediate_size=37, # layer_norm_eps=1e-05, # num_attention_heads=4, # num_hidden_layers=5, # vocab_size=5002, # ) # text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config) torch.manual_seed(0 ) snake_case__ : Dict = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , projection_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_0_0_2 , ) snake_case__ : int = CLIPTextModel(__lowerCamelCase ) snake_case__ : str = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""" ) snake_case__ : Union[str, Any] = 7_7 snake_case__ : str = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def lowercase ( self : int , __a : int , __a : str=0 ): if str(__lowerCamelCase ).startswith("""mps""" ): snake_case__ : Tuple = torch.manual_seed(__lowerCamelCase ) else: snake_case__ : Any = torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase ) snake_case__ : Optional[Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def lowercase ( self : Union[str, Any] ): super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 ) def lowercase ( self : Optional[int] ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def lowercase ( self : Tuple ): snake_case__ : List[str] = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case__ : int = self.get_dummy_components() torch.manual_seed(0 ) snake_case__ : str = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_0_0_2 , ) # TODO: remove after fixing the non-deterministic text encoder snake_case__ : Any = RobertaSeriesModelWithTransformation(__lowerCamelCase ) snake_case__ : List[str] = text_encoder snake_case__ : List[Any] = AltDiffusionPipeline(**__lowerCamelCase ) snake_case__ : Optional[Any] = alt_pipe.to(__lowerCamelCase ) alt_pipe.set_progress_bar_config(disable=__lowerCamelCase ) snake_case__ : List[str] = self.get_dummy_inputs(__lowerCamelCase ) snake_case__ : str = '''A photo of an astronaut''' snake_case__ : Any = alt_pipe(**__lowerCamelCase ) snake_case__ : int = output.images snake_case__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) snake_case__ : Optional[Any] = np.array( [0.5748162, 0.60447145, 0.48821217, 0.50100636, 0.5431185, 0.45763683, 0.49657696, 0.48132733, 0.47573093] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self : Tuple ): snake_case__ : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case__ : str = self.get_dummy_components() snake_case__ : Optional[Any] = PNDMScheduler(skip_prk_steps=__lowerCamelCase ) torch.manual_seed(0 ) snake_case__ : int = RobertaSeriesConfig( hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_0_0_2 , ) # TODO: remove after fixing the non-deterministic text encoder snake_case__ : Tuple = RobertaSeriesModelWithTransformation(__lowerCamelCase ) snake_case__ : List[str] = text_encoder snake_case__ : List[Any] = AltDiffusionPipeline(**__lowerCamelCase ) snake_case__ : str = alt_pipe.to(__lowerCamelCase ) alt_pipe.set_progress_bar_config(disable=__lowerCamelCase ) snake_case__ : Union[str, Any] = self.get_dummy_inputs(__lowerCamelCase ) snake_case__ : Optional[int] = alt_pipe(**__lowerCamelCase ) snake_case__ : Optional[int] = output.images snake_case__ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) snake_case__ : Union[str, Any] = np.array( [0.51605093, 0.5707241, 0.47365507, 0.50578886, 0.5633877, 0.4642503, 0.5182081, 0.48763484, 0.49084237] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class lowercase__ (unittest.TestCase ): """simple docstring""" def lowercase ( self : Union[str, Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self : int ): snake_case__ : Union[str, Any] = AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion""" , safety_checker=__lowerCamelCase ) snake_case__ : List[Any] = alt_pipe.to(__lowerCamelCase ) alt_pipe.set_progress_bar_config(disable=__lowerCamelCase ) snake_case__ : Any = '''A painting of a squirrel eating a burger''' snake_case__ : List[Any] = torch.manual_seed(0 ) snake_case__ : str = alt_pipe([prompt] , generator=__lowerCamelCase , guidance_scale=6.0 , num_inference_steps=2_0 , output_type="""np""" ) snake_case__ : str = output.images snake_case__ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) snake_case__ : Dict = np.array([0.1010, 0.0800, 0.0794, 0.0885, 0.0843, 0.0762, 0.0769, 0.0729, 0.0586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def lowercase ( self : str ): snake_case__ : List[Any] = DDIMScheduler.from_pretrained("""BAAI/AltDiffusion""" , subfolder="""scheduler""" ) snake_case__ : List[str] = AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion""" , scheduler=__lowerCamelCase , safety_checker=__lowerCamelCase ) snake_case__ : Union[str, Any] = alt_pipe.to(__lowerCamelCase ) alt_pipe.set_progress_bar_config(disable=__lowerCamelCase ) snake_case__ : List[Any] = '''A painting of a squirrel eating a burger''' snake_case__ : Optional[Any] = torch.manual_seed(0 ) snake_case__ : List[str] = alt_pipe([prompt] , generator=__lowerCamelCase , num_inference_steps=2 , output_type="""numpy""" ) snake_case__ : List[str] = output.images snake_case__ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) snake_case__ : List[Any] = np.array([0.4019, 0.4052, 0.3810, 0.4119, 0.3916, 0.3982, 0.4651, 0.4195, 0.5323] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
702
from __future__ import annotations from typing import Any class lowercase__ : """simple docstring""" def __init__( self : str , __a : int ): snake_case__ : Any = num_of_nodes snake_case__ : list[list[int]] = [] snake_case__ : dict[int, int] = {} def lowercase ( self : Any , __a : int , __a : int , __a : int ): self.m_edges.append([u_node, v_node, weight] ) def lowercase ( self : int , __a : int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def lowercase ( self : Dict , __a : int ): if self.m_component[u_node] != u_node: for k in self.m_component: snake_case__ : Optional[Any] = self.find_component(__a ) def lowercase ( self : Union[str, Any] , __a : list[int] , __a : int , __a : int ): if component_size[u_node] <= component_size[v_node]: snake_case__ : int = v_node component_size[v_node] += component_size[u_node] self.set_component(__a ) elif component_size[u_node] >= component_size[v_node]: snake_case__ : Any = self.find_component(__a ) component_size[u_node] += component_size[v_node] self.set_component(__a ) def lowercase ( self : int ): snake_case__ : Tuple = [] snake_case__ : Optional[Any] = 0 snake_case__ : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) snake_case__ : int = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: snake_case__ , snake_case__ , snake_case__ : List[Any] = edge snake_case__ : int = self.m_component[u] snake_case__ : Tuple = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): snake_case__ : int = [u, v, w] for edge in minimum_weight_edge: if isinstance(__a , __a ): snake_case__ , snake_case__ , snake_case__ : Union[str, Any] = edge snake_case__ : Optional[int] = self.m_component[u] snake_case__ : Tuple = self.m_component[v] if u_component != v_component: mst_weight += w self.union(__a , __a , __a ) print(f'Added edge [{u} - {v}]\nAdded weight: {w}\n' ) num_of_components -= 1 snake_case__ : Union[str, Any] = [-1] * self.m_num_of_nodes print(f'The total weight of the minimal spanning tree is: {mst_weight}' ) def _lowercase ( ): """simple docstring""" if __name__ == "__main__": import doctest doctest.testmod()
127
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json", } class lowercase ( lowerCAmelCase__ ): _a = "mgp-str" def __init__( self , _a=[32, 128] , _a=4 , _a=3 , _a=27 , _a=38 , _a=5_0257 , _a=3_0522 , _a=768 , _a=12 , _a=12 , _a=4.0 , _a=True , _a=False , _a=1e-5 , _a=0.0 , _a=0.0 , _a=0.0 , _a=False , _a=0.02 , **_a , ) -> List[str]: super().__init__(**_A ) _A : List[Any] = image_size _A : str = patch_size _A : List[Any] = num_channels _A : Tuple = max_token_length _A : Dict = num_character_labels _A : Any = num_bpe_labels _A : Any = num_wordpiece_labels _A : Optional[int] = hidden_size _A : List[Any] = num_hidden_layers _A : List[Any] = num_attention_heads _A : List[Any] = mlp_ratio _A : Union[str, Any] = distilled _A : Tuple = layer_norm_eps _A : List[Any] = drop_rate _A : Dict = qkv_bias _A : List[Any] = attn_drop_rate _A : Tuple = drop_path_rate _A : Any = output_aa_attentions _A : Tuple = initializer_range
307
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging lowercase_ = logging.get_logger(__name__) def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = set() __SCREAMING_SNAKE_CASE : str = [] def parse_line(snake_case ): for line in fp: if isinstance(snake_case , snake_case ): __SCREAMING_SNAKE_CASE : List[Any] = line.decode('''UTF-8''' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(''' ''' ): # process a single warning and move it to `selected_warnings`. if len(snake_case ) > 0: __SCREAMING_SNAKE_CASE : List[Any] = '''\n'''.join(snake_case ) # Only keep the warnings specified in `targets` if any(F''': {x}: ''' in warning for x in targets ): selected_warnings.add(snake_case ) buffer.clear() continue else: __SCREAMING_SNAKE_CASE : int = line.strip() buffer.append(snake_case ) if from_gh: for filename in os.listdir(snake_case ): __SCREAMING_SNAKE_CASE : Any = os.path.join(snake_case , snake_case ) if not os.path.isdir(snake_case ): # read the file if filename != "warnings.txt": continue with open(snake_case ) as fp: parse_line(snake_case ) else: try: with zipfile.ZipFile(snake_case ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case ): # read the file if filename != "warnings.txt": continue with z.open(snake_case ) as fp: parse_line(snake_case ) except Exception: logger.warning( F'''{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.''' ) return selected_warnings def a__ ( snake_case , snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = set() __SCREAMING_SNAKE_CASE : List[Any] = [os.path.join(snake_case , snake_case ) for p in os.listdir(snake_case ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(snake_case , snake_case ) ) return selected_warnings if __name__ == "__main__": def a__ ( snake_case ): """simple docstring""" return values.split(''',''' ) lowercase_ = 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.""") # optional parameters parser.add_argument( """--targets""", default="""DeprecationWarning,UserWarning,FutureWarning""", type=list_str, help="""Comma-separated list of target warning(s) which we want to extract.""", ) parser.add_argument( """--from_gh""", action="""store_true""", help="""If running from a GitHub action workflow and collecting warnings from its artifacts.""", ) lowercase_ = parser.parse_args() lowercase_ = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links lowercase_ = 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) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts lowercase_ = extract_warnings(args.output_dir, args.targets) lowercase_ = sorted(selected_warnings) with open(os.path.join(args.output_dir, """selected_warnings.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
74
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 ): """simple docstring""" def lowerCamelCase__ ( self : Tuple , snake_case : List[Any] , snake_case : str , snake_case : Union[str, Any] ) -> List[Any]: self.assertEqual(len(snake_case ) , len(snake_case ) ) for a, b in zip(snake_case , snake_case ): self.assertAlmostEqual(snake_case , snake_case , delta=snake_case ) def lowerCamelCase__ ( self : Optional[int] ) -> Union[str, Any]: __UpperCAmelCase : Union[str, Any] = 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(snake_case ): 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 lowerCamelCase__ ( self : int ) -> Union[str, Any]: __UpperCAmelCase : Dict = None ops.enable_eager_execution_internal() __UpperCAmelCase : Any = tf.config.list_physical_devices('''CPU''' ) if len(snake_case ) == 1: tf.config.set_logical_device_configuration( physical_devices[0] , [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] ) __UpperCAmelCase : Optional[Any] = tf.config.list_logical_devices(device_type='''CPU''' ) __UpperCAmelCase : Dict = tf.distribute.MirroredStrategy(devices=devices[:2] ) with strategy.scope(): __UpperCAmelCase : List[str] = GradientAccumulator() __UpperCAmelCase : Optional[Any] = tf.Variable([4.0, 3.0] ) __UpperCAmelCase , __UpperCAmelCase : Tuple = create_optimizer(5E-5 , 10 , 5 ) __UpperCAmelCase : int = tf.Variable([0.0, 0.0] , trainable=snake_case ) def accumulate_on_replica(snake_case : List[str] ): accumulator([gradient] ) def apply_on_replica(): optimizer.apply_gradients(list(zip(accumulator.gradients , [variable] ) ) ) @tf.function def accumulate(snake_case : Tuple , snake_case : Optional[Any] ): with strategy.scope(): __UpperCAmelCase : Optional[Any] = strategy.experimental_local_results(snake_case ) local_variables[0].assign(snake_case ) local_variables[1].assign(snake_case ) strategy.run(snake_case , args=(gradient_placeholder,) ) @tf.function def apply_grad(): with strategy.scope(): strategy.run(snake_case ) def _check_local_values(snake_case : List[str] , snake_case : Tuple ): __UpperCAmelCase : List[str] = strategy.experimental_local_results(accumulator._gradients[0] ) self.assertListAlmostEqual(values[0].value() , snake_case , tol=1E-2 ) self.assertListAlmostEqual(values[1].value() , snake_case , 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] )
266
'''simple docstring''' def _a ( _lowercase : list[list[int]] , _lowercase : int , _lowercase : int , _lowercase : set ): '''simple docstring''' __UpperCAmelCase , __UpperCAmelCase : Any = len(_lowercase ), len(grid[0] ) if ( min(_lowercase , _lowercase ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) __UpperCAmelCase : Optional[Any] = 0 count += depth_first_search(_lowercase , row + 1 , _lowercase , _lowercase ) count += depth_first_search(_lowercase , row - 1 , _lowercase , _lowercase ) count += depth_first_search(_lowercase , _lowercase , col + 1 , _lowercase ) count += depth_first_search(_lowercase , _lowercase , col - 1 , _lowercase ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
266
1
'''simple docstring''' import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors UpperCAmelCase = logging.getLogger(__name__) class lowerCAmelCase ( snake_case_ ): lowerCAmelCase_ = '''sequence-classification''' def __init__( self : Tuple , __lowercase : Optional[Any] ): """simple docstring""" if type(UpperCamelCase__ ) == dict: __lowercase =Namespace(**UpperCamelCase__ ) __lowercase =glue_output_modes[hparams.task] __lowercase =glue_tasks_num_labels[hparams.task] super().__init__(UpperCamelCase__ , UpperCamelCase__ , self.mode ) def snake_case ( self : int , **__lowercase : Tuple ): """simple docstring""" return self.model(**UpperCamelCase__ ) def snake_case ( self : List[str] , __lowercase : Any , __lowercase : Dict ): """simple docstring""" __lowercase ={"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __lowercase =batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __lowercase =self(**UpperCamelCase__ ) __lowercase =outputs[0] __lowercase =self.trainer.lr_schedulers[0]["scheduler"] __lowercase ={"loss": loss, "rate": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def snake_case ( self : List[str] ): """simple docstring""" __lowercase =self.hparams __lowercase =processors[args.task]() __lowercase =processor.get_labels() for mode in ["train", "dev"]: __lowercase =self._feature_file(UpperCamelCase__ ) if os.path.exists(UpperCamelCase__ ) and not args.overwrite_cache: logger.info('Loading features from cached file %s' , UpperCamelCase__ ) else: logger.info('Creating features from dataset file at %s' , args.data_dir ) __lowercase =( processor.get_dev_examples(args.data_dir ) if mode == "dev" else processor.get_train_examples(args.data_dir ) ) __lowercase =convert_examples_to_features( UpperCamelCase__ , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info('Saving features into cached file %s' , UpperCamelCase__ ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) def snake_case ( self : str , __lowercase : Tuple , __lowercase : Any , __lowercase : str = False ): """simple docstring""" __lowercase ="dev" if mode == "test" else mode __lowercase =self._feature_file(UpperCamelCase__ ) logger.info('Loading features from cached file %s' , UpperCamelCase__ ) __lowercase =torch.load(UpperCamelCase__ ) __lowercase =torch.tensor([f.input_ids for f in features] , dtype=torch.long ) __lowercase =torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) __lowercase =torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __lowercase =torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __lowercase =torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) , batch_size=UpperCamelCase__ , shuffle=UpperCamelCase__ , ) def snake_case ( self : List[str] , __lowercase : Optional[int] , __lowercase : str ): """simple docstring""" __lowercase ={"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __lowercase =batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __lowercase =self(**UpperCamelCase__ ) __lowercase =outputs[:2] __lowercase =logits.detach().cpu().numpy() __lowercase =inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def snake_case ( self : Optional[Any] , __lowercase : Union[str, Any] ): """simple docstring""" __lowercase =torch.stack([x['val_loss'] for x in outputs] ).mean().detach().cpu().item() __lowercase =np.concatenate([x['pred'] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": __lowercase =np.argmax(UpperCamelCase__ , axis=1 ) elif self.hparams.glue_output_mode == "regression": __lowercase =np.squeeze(UpperCamelCase__ ) __lowercase =np.concatenate([x['target'] for x in outputs] , axis=0 ) __lowercase =[[] for _ in range(out_label_ids.shape[0] )] __lowercase =[[] for _ in range(out_label_ids.shape[0] )] __lowercase ={**{"val_loss": val_loss_mean}, **compute_metrics(self.hparams.task , UpperCamelCase__ , UpperCamelCase__ )} __lowercase =dict(results.items() ) __lowercase =results return ret, preds_list, out_label_list def snake_case ( self : int , __lowercase : List[str] ): """simple docstring""" __lowercase =self._eval_end(UpperCamelCase__ ) __lowercase =ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def snake_case ( self : List[Any] , __lowercase : Optional[int] ): """simple docstring""" __lowercase =self._eval_end(UpperCamelCase__ ) __lowercase =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 snake_case ( __lowercase : Optional[Any] , __lowercase : List[str] ): """simple docstring""" BaseTransformer.add_model_specific_args(UpperCamelCase__ , UpperCamelCase__ ) parser.add_argument( '--max_seq_length' , default=128 , type=UpperCamelCase__ , help=( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) , ) parser.add_argument( '--task' , default='' , type=UpperCamelCase__ , required=UpperCamelCase__ , help='The GLUE task to run' , ) parser.add_argument( '--gpus' , default=0 , type=UpperCamelCase__ , 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 def __UpperCamelCase ( ): '''simple docstring''' __lowercase =argparse.ArgumentParser() add_generic_args(lowercase__, os.getcwd() ) __lowercase =GLUETransformer.add_model_specific_args(lowercase__, os.getcwd() ) __lowercase =parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __lowercase =os.path.join( './results', F'''{args.task}_{time.strftime("%Y%m%d_%H%M%S" )}''', ) os.makedirs(args.output_dir ) __lowercase =GLUETransformer(lowercase__ ) __lowercase =generic_train(lowercase__, lowercase__ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __lowercase =sorted(glob.glob(os.path.join(args.output_dir, 'checkpoint-epoch=*.ckpt' ), recursive=lowercase__ ) ) __lowercase =model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(lowercase__ ) if __name__ == "__main__": main()
119
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __snake_case = { """configuration_poolformer""": [ """POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PoolFormerConfig""", """PoolFormerOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""PoolFormerFeatureExtractor"""] __snake_case = ["""PoolFormerImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """PoolFormerForImageClassification""", """PoolFormerModel""", """PoolFormerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_poolformer import ( POOLFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, PoolFormerConfig, PoolFormerOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_poolformer import PoolFormerFeatureExtractor from .image_processing_poolformer import PoolFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_poolformer import ( POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, PoolFormerForImageClassification, PoolFormerModel, PoolFormerPreTrainedModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
178
0
def __lowerCAmelCase ( A_ : int , A_ : int ) -> int: __UpperCAmelCase = 1 # To kept the Calculated Value # Since C(n, k) = C(n, n-k) if k > (n - k): __UpperCAmelCase = n - k # Calculate C(n,k) for i in range(A_ ): result *= n - i result //= i + 1 return result def __lowerCAmelCase ( A_ : int ) -> int: return binomial_coefficient(2 * node_count , A_ ) // (node_count + 1) def __lowerCAmelCase ( A_ : int ) -> int: if n < 0: raise ValueError("factorial() not defined for negative values" ) __UpperCAmelCase = 1 for i in range(1 , n + 1 ): result *= i return result def __lowerCAmelCase ( A_ : int ) -> int: return catalan_number(A_ ) * factorial(A_ ) if __name__ == "__main__": a_ = int(input("""Enter the number of nodes: """).strip() or 0) if node_count <= 0: raise ValueError("""We need some nodes to work with.""") print( F"Given {node_count} nodes, there are {binary_tree_count(node_count)} " F"binary trees and {catalan_number(node_count)} binary search trees." )
286
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { """facebook/vit-mae-base""": """https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json""", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class UpperCAmelCase__ ( snake_case ): """simple docstring""" lowerCAmelCase__ : Dict = 'vit_mae' def __init__( self: List[Any] , __lowerCAmelCase: Any=768 , __lowerCAmelCase: List[str]=12 , __lowerCAmelCase: Optional[int]=12 , __lowerCAmelCase: Tuple=3_072 , __lowerCAmelCase: List[Any]="gelu" , __lowerCAmelCase: Dict=0.0 , __lowerCAmelCase: Tuple=0.0 , __lowerCAmelCase: Any=0.02 , __lowerCAmelCase: List[Any]=1E-12 , __lowerCAmelCase: List[str]=224 , __lowerCAmelCase: Optional[Any]=16 , __lowerCAmelCase: Union[str, Any]=3 , __lowerCAmelCase: Tuple=True , __lowerCAmelCase: Union[str, Any]=16 , __lowerCAmelCase: Optional[int]=512 , __lowerCAmelCase: int=8 , __lowerCAmelCase: int=2_048 , __lowerCAmelCase: str=0.75 , __lowerCAmelCase: Union[str, Any]=False , **__lowerCAmelCase: List[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**__lowerCAmelCase ) __UpperCAmelCase = hidden_size __UpperCAmelCase = num_hidden_layers __UpperCAmelCase = num_attention_heads __UpperCAmelCase = intermediate_size __UpperCAmelCase = hidden_act __UpperCAmelCase = hidden_dropout_prob __UpperCAmelCase = attention_probs_dropout_prob __UpperCAmelCase = initializer_range __UpperCAmelCase = layer_norm_eps __UpperCAmelCase = image_size __UpperCAmelCase = patch_size __UpperCAmelCase = num_channels __UpperCAmelCase = qkv_bias __UpperCAmelCase = decoder_num_attention_heads __UpperCAmelCase = decoder_hidden_size __UpperCAmelCase = decoder_num_hidden_layers __UpperCAmelCase = decoder_intermediate_size __UpperCAmelCase = mask_ratio __UpperCAmelCase = norm_pix_loss
286
1
'''simple docstring''' import sys lowercase__ = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ = N ) -> int: '''simple docstring''' snake_case : List[str] = -sys.maxsize - 1 for i in range(len(a_ ) - 12 ): snake_case : Optional[Any] = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: snake_case : str = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
638
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar lowercase = TypeVar("T") class UpperCamelCase_ ( Generic[T] ): '''simple docstring''' lowerCAmelCase = 42 # Cache store of keys lowerCAmelCase = 42 # References of the keys in cache lowerCAmelCase = 1_0 # Maximum capacity of cache def __init__( self , a ) -> None: snake_case_ = deque() snake_case_ = set() if not n: snake_case_ = sys.maxsize elif n < 0: raise ValueError('n should be an integer greater than 0.' ) else: snake_case_ = n def _UpperCamelCase ( self , a ) -> None: if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: snake_case_ = self.dq_store.pop() self.key_reference.remove(a ) else: self.dq_store.remove(a ) self.dq_store.appendleft(a ) self.key_reference.add(a ) def _UpperCamelCase ( self ) -> None: for k in self.dq_store: print(a ) def __repr__( self ) -> str: return F'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}''' if __name__ == "__main__": import doctest doctest.testmod() lowercase = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
198
0
'''simple docstring''' import unittest from transformers import AutoTokenizer, NystromformerConfig, 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 ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase : '''simple docstring''' def __init__( self : Tuple ,_a : Tuple ,_a : Optional[Any]=13 ,_a : Optional[int]=7 ,_a : Optional[Any]=True ,_a : Optional[Any]=True ,_a : List[str]=True ,_a : str=True ,_a : Dict=99 ,_a : Optional[int]=32 ,_a : Optional[int]=5 ,_a : int=4 ,_a : Tuple=37 ,_a : int="gelu" ,_a : Tuple=0.1 ,_a : Union[str, Any]=0.1 ,_a : Optional[Any]=512 ,_a : Dict=16 ,_a : List[Any]=2 ,_a : Optional[Any]=0.02 ,_a : Union[str, Any]=3 ,_a : List[str]=4 ,_a : List[Any]=None ,): '''simple docstring''' A_ : Optional[int] = parent A_ : int = batch_size A_ : List[Any] = seq_length A_ : Tuple = is_training A_ : str = use_input_mask A_ : int = use_token_type_ids A_ : Dict = use_labels A_ : List[str] = vocab_size A_ : List[str] = hidden_size A_ : Dict = num_hidden_layers A_ : str = num_attention_heads A_ : int = intermediate_size A_ : Optional[Any] = hidden_act A_ : int = hidden_dropout_prob A_ : Dict = attention_probs_dropout_prob A_ : str = max_position_embeddings A_ : List[Any] = type_vocab_size A_ : List[str] = type_sequence_label_size A_ : List[Any] = initializer_range A_ : int = num_labels A_ : int = num_choices A_ : int = scope def _a ( self : Optional[int] ): '''simple docstring''' A_ : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A_ : int = None if self.use_input_mask: A_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) A_ : List[Any] = None if self.use_token_type_ids: A_ : str = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A_ : Union[str, Any] = None A_ : Dict = None A_ : Tuple = None if self.use_labels: A_ : Optional[Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) A_ : Tuple = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) A_ : Union[str, Any] = ids_tensor([self.batch_size] ,self.num_choices ) A_ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self : List[str] ): '''simple docstring''' return NystromformerConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=_a ,initializer_range=self.initializer_range ,) def _a ( self : str ,_a : List[str] ,_a : List[str] ,_a : Optional[Any] ,_a : Optional[Any] ,_a : List[str] ,_a : List[str] ,_a : List[Any] ): '''simple docstring''' A_ : Optional[int] = NystromformerModel(config=_a ) model.to(_a ) model.eval() A_ : Optional[Any] = model(_a ,attention_mask=_a ,token_type_ids=_a ) A_ : Any = model(_a ,token_type_ids=_a ) A_ : Tuple = model(_a ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self : Tuple ,_a : List[Any] ,_a : Dict ,_a : Tuple ,_a : Optional[Any] ,_a : Any ,_a : List[Any] ,_a : int ): '''simple docstring''' A_ : int = NystromformerForMaskedLM(config=_a ) model.to(_a ) model.eval() A_ : Tuple = model(_a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self : Any ,_a : Optional[Any] ,_a : Dict ,_a : Any ,_a : Optional[int] ,_a : str ,_a : Dict ,_a : List[str] ): '''simple docstring''' A_ : List[str] = NystromformerForQuestionAnswering(config=_a ) model.to(_a ) model.eval() A_ : Dict = model( _a ,attention_mask=_a ,token_type_ids=_a ,start_positions=_a ,end_positions=_a ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _a ( self : str ,_a : Optional[int] ,_a : List[str] ,_a : List[str] ,_a : Any ,_a : Tuple ,_a : Union[str, Any] ,_a : Union[str, Any] ): '''simple docstring''' A_ : Optional[Any] = self.num_labels A_ : Optional[int] = NystromformerForSequenceClassification(_a ) model.to(_a ) model.eval() A_ : List[Any] = model(_a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _a ( self : Optional[int] ,_a : List[Any] ,_a : int ,_a : Tuple ,_a : Optional[Any] ,_a : Any ,_a : Union[str, Any] ,_a : Tuple ): '''simple docstring''' A_ : List[str] = self.num_labels A_ : List[Any] = NystromformerForTokenClassification(config=_a ) model.to(_a ) model.eval() A_ : Dict = model(_a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _a ( self : int ,_a : Tuple ,_a : List[Any] ,_a : Optional[Any] ,_a : Any ,_a : Optional[int] ,_a : Tuple ,_a : Any ): '''simple docstring''' A_ : Optional[int] = self.num_choices A_ : Tuple = NystromformerForMultipleChoice(config=_a ) model.to(_a ) model.eval() A_ : int = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A_ : List[str] = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A_ : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() A_ : Optional[Any] = model( _a ,attention_mask=_a ,token_type_ids=_a ,labels=_a ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _a ( self : List[str] ): '''simple docstring''' A_ : Dict = self.prepare_config_and_inputs() ( A_ ) : str = config_and_inputs A_ : Dict = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' a_ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) a_ = ( { """feature-extraction""": NystromformerModel, """fill-mask""": NystromformerForMaskedLM, """question-answering""": NystromformerForQuestionAnswering, """text-classification""": NystromformerForSequenceClassification, """token-classification""": NystromformerForTokenClassification, """zero-shot""": NystromformerForSequenceClassification, } if is_torch_available() else {} ) a_ = False a_ = False def _a ( self : int ): '''simple docstring''' A_ : Any = NystromformerModelTester(self ) A_ : Any = ConfigTester(self ,config_class=_a ,hidden_size=37 ) def _a ( self : List[str] ): '''simple docstring''' self.config_tester.run_common_tests() def _a ( self : List[Any] ): '''simple docstring''' A_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_a ) def _a ( self : Optional[int] ): '''simple docstring''' A_ : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: A_ : List[str] = type self.model_tester.create_and_check_model(*_a ) def _a ( self : str ): '''simple docstring''' A_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_a ) def _a ( self : Tuple ): '''simple docstring''' A_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_a ) def _a ( self : Dict ): '''simple docstring''' A_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_a ) def _a ( self : Any ): '''simple docstring''' A_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_a ) def _a ( self : int ): '''simple docstring''' A_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_a ) @slow def _a ( self : int ): '''simple docstring''' for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A_ : Optional[int] = NystromformerModel.from_pretrained(_a ) self.assertIsNotNone(_a ) @require_torch class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def _a ( self : int ): '''simple docstring''' A_ : Optional[int] = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) A_ : int = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): A_ : int = model(_a )[0] A_ : Union[str, Any] = torch.Size((1, 6, 768) ) self.assertEqual(output.shape ,_a ) A_ : Tuple = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,_a ,atol=1e-4 ) ) @slow def _a ( self : Optional[int] ): '''simple docstring''' A_ : Tuple = """the [MASK] of Belgium is Brussels""" A_ : List[Any] = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) A_ : List[Any] = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) A_ : Tuple = tokenizer(_a ,return_tensors="""pt""" ) with torch.no_grad(): A_ : Union[str, Any] = model(encoding.input_ids ).logits A_ : str = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(_a ) ,"""capital""" )
704
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __magic_name__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['NllbTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ['NllbTokenizerFast'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys __magic_name__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
27
0
'''simple docstring''' import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = checkpoints.load_tax_checkpoint(__A ) __UpperCamelCase = flatten_dict(__A ) return flax_params def _lowercase ( __A ): '''simple docstring''' __UpperCamelCase = {} __UpperCamelCase = { """token_embedder""": """embeddings""", """encoder_norm""": """layernorm""", """kernel""": """weight""", """.out""": """.output""", """scale""": """weight""", """embedders_0.pos_embedding""": """row_embedder.weight""", """embedders_1.pos_embedding""": """column_embedder.weight""", } __UpperCamelCase = { """query""": """attention.query""", """key""": """attention.key""", """value""": """attention.value""", """output.dense""": """output""", """encoder_decoder_attention.o""": """encoder_decoder_attention.attention.o""", """pre_self_attention_layer_norm""": """self_attention.layer_norm""", """pre_cross_attention_layer_norm""": """encoder_decoder_attention.layer_norm""", """mlp.""": """mlp.DenseReluDense.""", """pre_mlp_layer_norm""": """mlp.layer_norm""", """self_attention.o""": """self_attention.attention.o""", """decoder.embeddings.embedding""": """decoder.embed_tokens.weight""", """decoder.relpos_bias.rel_embedding""": """decoder.layer.0.self_attention.attention.relative_attention_bias.weight""", """decoder.decoder_norm.weight""": """decoder.final_layer_norm.weight""", """decoder.logits_dense.weight""": """decoder.lm_head.weight""", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __UpperCamelCase = """.""".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __UpperCamelCase = new_key.replace(__A ,__A ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __UpperCamelCase = new_key.replace(__A ,__A ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __UpperCamelCase = re.sub(R"""layers_(\d+)""" ,R"""layer.\1""" ,__A ) __UpperCamelCase = new_key.replace("""encoder""" ,"""encoder.encoder""" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __UpperCamelCase = re.sub(R"""layers_(\d+)""" ,R"""layer.\1""" ,__A ) __UpperCamelCase = flax_dict[key] __UpperCamelCase = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __UpperCamelCase = torch.from_numpy(converted_dict[key].T ) else: __UpperCamelCase = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def _lowercase ( __A ,__A ,__A=False ,__A=False ): '''simple docstring''' __UpperCamelCase = get_flax_param(__A ) if not use_large: __UpperCamelCase = PixaStructVisionConfig() __UpperCamelCase = PixaStructTextConfig() else: __UpperCamelCase = PixaStructVisionConfig( hidden_size=1_536 ,d_ff=3_968 ,num_attention_heads=24 ,num_hidden_layers=18 ) __UpperCamelCase = PixaStructTextConfig(hidden_size=1_536 ,d_ff=3_968 ,num_heads=24 ,num_layers=18 ) __UpperCamelCase = PixaStructConfig( vision_config=encoder_config.to_dict() ,text_config=decoder_config.to_dict() ,is_vqa=__A ) __UpperCamelCase = PixaStructForConditionalGeneration(__A ) __UpperCamelCase = rename_and_convert_flax_params(__A ) model.load_state_dict(__A ) __UpperCamelCase = AutoTokenizer.from_pretrained("""ybelkada/test-pix2struct-tokenizer""" ) __UpperCamelCase = PixaStructImageProcessor() __UpperCamelCase = PixaStructProcessor(image_processor=__A ,tokenizer=__A ) if use_large: __UpperCamelCase = 4_096 __UpperCamelCase = True # mkdir if needed os.makedirs(__A ,exist_ok=__A ) model.save_pretrained(__A ) processor.save_pretrained(__A ) print("""Model saved in {}""".format(__A ) ) if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument('--t5x_checkpoint_path', default=None, type=str, help='Path to the original T5x checkpoint.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--use_large', action='store_true', help='Use large model.') parser.add_argument('--is_vqa', action='store_true', help='Use large model.') a__ : Any = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
601
'''simple docstring''' # using dfs for finding eulerian path traversal def _lowercase ( __A ,__A ,__A ,__A=None ): '''simple docstring''' __UpperCamelCase = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: __UpperCamelCase , __UpperCamelCase = True, True __UpperCamelCase = dfs(__A ,__A ,__A ,__A ) return path def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = 0 __UpperCamelCase = -1 for i in range(__A ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 __UpperCamelCase = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def _lowercase ( __A ,__A ): '''simple docstring''' __UpperCamelCase = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] __UpperCamelCase , __UpperCamelCase = check_circuit_or_path(__A ,__A ) if check == 3: print("""graph is not Eulerian""" ) print("""no path""" ) return __UpperCamelCase = 1 if check == 2: __UpperCamelCase = odd_node print("""graph has a Euler path""" ) if check == 1: print("""graph has a Euler cycle""" ) __UpperCamelCase = dfs(__A ,__A ,__A ) print(__A ) def _lowercase ( ): '''simple docstring''' __UpperCamelCase = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} __UpperCamelCase = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} __UpperCamelCase = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} __UpperCamelCase = {1: [2, 3], 2: [1, 3], 3: [1, 2]} __UpperCamelCase = { 1: [], 2: [] # all degree is zero } __UpperCamelCase = 10 check_euler(__A ,__A ) check_euler(__A ,__A ) check_euler(__A ,__A ) check_euler(__A ,__A ) check_euler(__A ,__A ) if __name__ == "__main__": main()
601
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType _lowerCamelCase : Any = logging.get_logger(__name__) _lowerCamelCase : List[Any] = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off _lowerCamelCase : List[str] = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 3_57, 3_66, 4_38, 5_32, 6_85, 7_05, 7_96, 9_30, 10_58, 12_20, 12_67, 12_79, 13_03, 13_43, 13_77, 13_91, 16_35, 17_82, 18_75, 21_62, 23_61, 24_88, 34_67, 40_08, 42_11, 46_00, 48_08, 52_99, 58_55, 63_29, 72_03, 96_09, 99_59, 1_05_63, 1_07_86, 1_14_20, 1_17_09, 1_19_07, 1_31_63, 1_36_97, 1_37_00, 1_48_08, 1_53_06, 1_64_10, 1_67_91, 1_79_92, 1_92_03, 1_95_10, 2_07_24, 2_23_05, 2_29_35, 2_70_07, 3_01_09, 3_04_20, 3_34_09, 3_49_49, 4_02_83, 4_04_93, 4_05_49, 4_72_82, 4_91_46, 5_02_57, 5_03_59, 5_03_60, 5_03_61 ] _lowerCamelCase : Any = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 3_59, 5_03, 5_22, 5_42, 8_73, 8_93, 9_02, 9_18, 9_22, 9_31, 13_50, 18_53, 19_82, 24_60, 26_27, 32_46, 32_53, 32_68, 35_36, 38_46, 39_61, 41_83, 46_67, 65_85, 66_47, 72_73, 90_61, 93_83, 1_04_28, 1_09_29, 1_19_38, 1_20_33, 1_23_31, 1_25_62, 1_37_93, 1_41_57, 1_46_35, 1_52_65, 1_56_18, 1_65_53, 1_66_04, 1_83_62, 1_89_56, 2_00_75, 2_16_75, 2_25_20, 2_61_30, 2_61_61, 2_64_35, 2_82_79, 2_94_64, 3_16_50, 3_23_02, 3_24_70, 3_68_65, 4_28_63, 4_74_25, 4_98_70, 5_02_54, 5_02_58, 5_03_60, 5_03_61, 5_03_62 ] class lowerCamelCase__ ( __snake_case ): __UpperCAmelCase = """whisper""" __UpperCAmelCase = ["""past_key_values"""] __UpperCAmelCase = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCAmelCase__=51_865 , lowerCAmelCase__=80 , lowerCAmelCase__=6 , lowerCAmelCase__=4 , lowerCAmelCase__=6 , lowerCAmelCase__=4 , lowerCAmelCase__=1_536 , lowerCAmelCase__=1_536 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=50_257 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__="gelu" , lowerCAmelCase__=256 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.02 , lowerCAmelCase__=False , lowerCAmelCase__=1_500 , lowerCAmelCase__=448 , lowerCAmelCase__=50_256 , lowerCAmelCase__=50_256 , lowerCAmelCase__=50_256 , lowerCAmelCase__=None , lowerCAmelCase__=[220, 50_256] , lowerCAmelCase__=False , lowerCAmelCase__=256 , lowerCAmelCase__=False , lowerCAmelCase__=0.05 , lowerCAmelCase__=10 , lowerCAmelCase__=2 , lowerCAmelCase__=0.0 , lowerCAmelCase__=10 , lowerCAmelCase__=0 , lowerCAmelCase__=7 , **lowerCAmelCase__ , ) -> List[Any]: """simple docstring""" _UpperCamelCase :List[str] =vocab_size _UpperCamelCase :Dict =num_mel_bins _UpperCamelCase :Union[str, Any] =d_model _UpperCamelCase :Dict =encoder_layers _UpperCamelCase :Optional[Any] =encoder_attention_heads _UpperCamelCase :Union[str, Any] =decoder_layers _UpperCamelCase :Any =decoder_attention_heads _UpperCamelCase :int =decoder_ffn_dim _UpperCamelCase :List[Any] =encoder_ffn_dim _UpperCamelCase :Any =dropout _UpperCamelCase :Tuple =attention_dropout _UpperCamelCase :Dict =activation_dropout _UpperCamelCase :Any =activation_function _UpperCamelCase :List[Any] =init_std _UpperCamelCase :Tuple =encoder_layerdrop _UpperCamelCase :Optional[Any] =decoder_layerdrop _UpperCamelCase :int =use_cache _UpperCamelCase :Tuple =encoder_layers _UpperCamelCase :List[Any] =scale_embedding # scale factor will be sqrt(d_model) if True _UpperCamelCase :List[Any] =max_source_positions _UpperCamelCase :List[str] =max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. _UpperCamelCase :Optional[int] =classifier_proj_size _UpperCamelCase :Optional[int] =use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _UpperCamelCase :List[str] =apply_spec_augment _UpperCamelCase :int =mask_time_prob _UpperCamelCase :Union[str, Any] =mask_time_length _UpperCamelCase :str =mask_time_min_masks _UpperCamelCase :int =mask_feature_prob _UpperCamelCase :Optional[Any] =mask_feature_length _UpperCamelCase :Optional[int] =mask_feature_min_masks _UpperCamelCase :Optional[Any] =median_filter_width super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , is_encoder_decoder=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , suppress_tokens=lowerCAmelCase__ , begin_suppress_tokens=lowerCAmelCase__ , **lowerCAmelCase__ , ) class lowerCamelCase__ ( __snake_case ): @property def _UpperCamelCase ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" _UpperCamelCase :List[Any] =OrderedDict( [ ("""input_features""", {0: """batch""", 1: """feature_size""", 2: """encoder_sequence"""}), ] ) if self.use_past: _UpperCamelCase :Tuple ={0: """batch"""} else: _UpperCamelCase :Optional[Any] ={0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(lowerCAmelCase__ , direction="""inputs""" ) return common_inputs def _UpperCamelCase ( self , lowerCAmelCase__ , lowerCAmelCase__ = -1 , lowerCAmelCase__ = -1 , lowerCAmelCase__ = False , lowerCAmelCase__ = None , lowerCAmelCase__ = 22_050 , lowerCAmelCase__ = 5.0 , lowerCAmelCase__ = 220 , ) -> Mapping[str, Any]: """simple docstring""" _UpperCamelCase :Tuple =OrderedDict() _UpperCamelCase :List[Any] =OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=lowerCAmelCase__ , framework=lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , time_duration=lowerCAmelCase__ , frequency=lowerCAmelCase__ , ) _UpperCamelCase :List[str] =encoder_inputs["""input_features"""].shape[2] _UpperCamelCase :Tuple =encoder_sequence_length // 2 if self.use_past else seq_length _UpperCamelCase :int =super().generate_dummy_inputs( preprocessor.tokenizer , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) _UpperCamelCase :Dict =encoder_inputs.pop("""input_features""" ) _UpperCamelCase :Any =decoder_inputs.pop("""decoder_input_ids""" ) if "past_key_values" in decoder_inputs: _UpperCamelCase :Tuple =decoder_inputs.pop("""past_key_values""" ) return dummy_inputs @property def _UpperCamelCase ( self ) -> float: """simple docstring""" return 1e-3
512
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Any = logging.get_logger(__name__) _lowerCamelCase : str = { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json""", } class lowerCamelCase__ ( __snake_case ): __UpperCAmelCase = """mvp""" __UpperCAmelCase = ["""past_key_values"""] __UpperCAmelCase = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCAmelCase__=50_267 , lowerCAmelCase__=1_024 , lowerCAmelCase__=12 , lowerCAmelCase__=4_096 , lowerCAmelCase__=16 , lowerCAmelCase__=12 , lowerCAmelCase__=4_096 , lowerCAmelCase__=16 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__="gelu" , lowerCAmelCase__=1_024 , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.0 , lowerCAmelCase__=0.02 , lowerCAmelCase__=0.0 , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , lowerCAmelCase__=True , lowerCAmelCase__=2 , lowerCAmelCase__=2 , lowerCAmelCase__=False , lowerCAmelCase__=100 , lowerCAmelCase__=800 , **lowerCAmelCase__ , ) -> Union[str, Any]: """simple docstring""" _UpperCamelCase :Dict =vocab_size _UpperCamelCase :List[Any] =max_position_embeddings _UpperCamelCase :Tuple =d_model _UpperCamelCase :List[Any] =encoder_ffn_dim _UpperCamelCase :Optional[int] =encoder_layers _UpperCamelCase :List[str] =encoder_attention_heads _UpperCamelCase :List[Any] =decoder_ffn_dim _UpperCamelCase :Union[str, Any] =decoder_layers _UpperCamelCase :int =decoder_attention_heads _UpperCamelCase :Union[str, Any] =dropout _UpperCamelCase :Tuple =attention_dropout _UpperCamelCase :Union[str, Any] =activation_dropout _UpperCamelCase :Optional[Any] =activation_function _UpperCamelCase :Dict =init_std _UpperCamelCase :Optional[Any] =encoder_layerdrop _UpperCamelCase :List[Any] =decoder_layerdrop _UpperCamelCase :Optional[int] =classifier_dropout _UpperCamelCase :Optional[Any] =use_cache _UpperCamelCase :List[Any] =encoder_layers _UpperCamelCase :List[str] =scale_embedding # scale factor will be sqrt(d_model) if True _UpperCamelCase :Dict =use_prompt _UpperCamelCase :Optional[Any] =prompt_length _UpperCamelCase :Tuple =prompt_mid_dim super().__init__( pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , is_encoder_decoder=lowerCAmelCase__ , decoder_start_token_id=lowerCAmelCase__ , forced_eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ , ) if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated""" , lowerCAmelCase__ ): _UpperCamelCase :Dict =self.bos_token_id warnings.warn( f'''Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ''' """The config can simply be saved and uploaded again to be fixed.""" )
512
1
"""simple docstring""" from __future__ import annotations import numpy as np def __magic_name__ ( __snake_case : np.ndarray ) -> Optional[int]: lowercase , lowercase : int = np.shape(UpperCamelCase__ ) if rows != columns: lowercase : List[Any] = ( "\'table\' has to be of square shaped array but got a " f"""{rows}x{columns} array:\n{table}""" ) raise ValueError(UpperCamelCase__ ) lowercase : Optional[Any] = np.zeros((rows, columns) ) lowercase : Dict = np.zeros((rows, columns) ) for i in range(UpperCamelCase__ ): for j in range(UpperCamelCase__ ): lowercase : Optional[Any] = sum(lower[i][k] * upper[k][j] for k in range(UpperCamelCase__ ) ) if upper[j][j] == 0: raise ArithmeticError("No LU decomposition exists" ) lowercase : List[Any] = (table[i][j] - total) / upper[j][j] lowercase : List[Any] = 1 for j in range(UpperCamelCase__ , UpperCamelCase__ ): lowercase : List[Any] = sum(lower[i][k] * upper[k][j] for k in range(UpperCamelCase__ ) ) lowercase : Any = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
361
'''simple docstring''' import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow __lowerCAmelCase : int = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ "text-classification", "language-modeling", "summarization", "token-classification", "question-answering", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) __lowerCAmelCase : List[Any] = logging.getLogger() def lowerCAmelCase ( ): """simple docstring""" __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument('''-f''' ) __UpperCAmelCase = parser.parse_args() return args.f def lowerCAmelCase ( UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Any="eval" ): """simple docstring""" __UpperCAmelCase = os.path.join(UpperCamelCase__ , f"""{split}_results.json""" ) if os.path.exists(UpperCamelCase__ ): with open(UpperCamelCase__ , '''r''' ) as f: return json.load(UpperCamelCase__ ) raise ValueError(f"""can't find {path}""" ) __lowerCAmelCase : str = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class A ( UpperCAmelCase ): def snake_case__ ( self : List[Any] ) -> Union[str, Any]: __UpperCAmelCase = self.get_auto_remove_tmp_dir() __UpperCAmelCase = f""" run_glue.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --eval_steps=2 --warmup_steps=2 --seed=42 --max_seq_length=128 """.split() with patch.object(__a , '''argv''' , __a ): run_flax_glue.main() __UpperCAmelCase = get_results(__a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.7_5 ) @slow def snake_case__ ( self : Optional[Any] ) -> Optional[int]: __UpperCAmelCase = self.get_auto_remove_tmp_dir() __UpperCAmelCase = f""" run_clm_flax.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --block_size 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(__a , '''argv''' , __a ): run_clm_flax.main() __UpperCAmelCase = get_results(__a ) self.assertLess(result['''eval_perplexity'''] , 1_0_0 ) @slow def snake_case__ ( self : Dict ) -> List[str]: __UpperCAmelCase = self.get_auto_remove_tmp_dir() __UpperCAmelCase = f""" run_summarization.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --test_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=8 --do_train --do_eval --do_predict --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --predict_with_generate """.split() with patch.object(__a , '''argv''' , __a ): run_summarization_flax.main() __UpperCAmelCase = get_results(__a , split='''test''' ) self.assertGreaterEqual(result['''test_rouge1'''] , 1_0 ) self.assertGreaterEqual(result['''test_rouge2'''] , 2 ) self.assertGreaterEqual(result['''test_rougeL'''] , 7 ) self.assertGreaterEqual(result['''test_rougeLsum'''] , 7 ) @slow def snake_case__ ( self : Any ) -> List[Any]: __UpperCAmelCase = self.get_auto_remove_tmp_dir() __UpperCAmelCase = f""" run_mlm.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --overwrite_output_dir --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --logging_steps 2 --eval_steps 2 --do_train --do_eval --num_train_epochs=1 """.split() with patch.object(__a , '''argv''' , __a ): run_mlm_flax.main() __UpperCAmelCase = get_results(__a ) self.assertLess(result['''eval_perplexity'''] , 4_2 ) @slow def snake_case__ ( self : Dict ) -> str: __UpperCAmelCase = self.get_auto_remove_tmp_dir() __UpperCAmelCase = f""" run_t5_mlm_flax.py --model_name_or_path t5-small --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --do_train --do_eval --max_seq_length 128 --per_device_train_batch_size 4 --per_device_eval_batch_size 4 --num_train_epochs 2 --logging_steps 2 --eval_steps 2 --output_dir {tmp_dir} --overwrite_output_dir """.split() with patch.object(__a , '''argv''' , __a ): run_ta_mlm_flax.main() __UpperCAmelCase = get_results(__a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.4_2 ) @slow def snake_case__ ( self : Dict ) -> Tuple: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu __UpperCAmelCase = 7 if get_gpu_count() > 1 else 2 __UpperCAmelCase = self.get_auto_remove_tmp_dir() __UpperCAmelCase = f""" run_flax_ner.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --overwrite_output_dir --do_train --do_eval --warmup_steps=2 --learning_rate=2e-4 --logging_steps 2 --eval_steps 2 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 """.split() with patch.object(__a , '''argv''' , __a ): run_flax_ner.main() __UpperCAmelCase = get_results(__a ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.7_5 ) self.assertGreaterEqual(result['''eval_f1'''] , 0.3 ) @slow def snake_case__ ( self : Optional[Any] ) -> List[Any]: __UpperCAmelCase = self.get_auto_remove_tmp_dir() __UpperCAmelCase = f""" run_qa.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --overwrite_output_dir --num_train_epochs=3 --warmup_steps=2 --do_train --do_eval --logging_steps 2 --eval_steps 2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 """.split() with patch.object(__a , '''argv''' , __a ): run_qa.main() __UpperCAmelCase = get_results(__a ) self.assertGreaterEqual(result['''eval_f1'''] , 3_0 ) self.assertGreaterEqual(result['''eval_exact'''] , 3_0 )
262
0
def a ( lowerCamelCase_ ): '''simple docstring''' lowercase__ = 1 lowercase__ = 2 while i * i <= n: lowercase__ = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def a ( ): '''simple docstring''' lowercase__ = 1 lowercase__ = 1 while True: i += 1 t_num += i if count_divisors(lowerCamelCase_ ) > 500: break return t_num if __name__ == "__main__": print(solution())
715
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision 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 MobileNetVaImageProcessor class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : str, lowerCamelCase : Any, lowerCamelCase : Tuple=7, lowerCamelCase : str=3, lowerCamelCase : Tuple=18, lowerCamelCase : int=30, lowerCamelCase : Tuple=400, lowerCamelCase : Any=True, lowerCamelCase : Any=None, lowerCamelCase : List[str]=True, lowerCamelCase : Union[str, Any]=None, ): '''simple docstring''' lowercase__ = size if size is not None else {'''shortest_edge''': 20} lowercase__ = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} lowercase__ = parent lowercase__ = batch_size lowercase__ = num_channels lowercase__ = image_size lowercase__ = min_resolution lowercase__ = max_resolution lowercase__ = do_resize lowercase__ = size lowercase__ = do_center_crop lowercase__ = crop_size def lowercase__ ( self : Any ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, } @require_torch @require_vision class _UpperCAmelCase ( A__ ,unittest.TestCase ): """simple docstring""" lowercase__ = MobileNetVaImageProcessor if is_vision_available() else None def lowercase__ ( self : Any ): '''simple docstring''' lowercase__ = MobileNetVaImageProcessingTester(self ) @property def lowercase__ ( self : Union[str, Any] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowercase__ ( self : Dict ): '''simple docstring''' lowercase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase, '''do_resize''' ) ) self.assertTrue(hasattr(lowerCamelCase, '''size''' ) ) self.assertTrue(hasattr(lowerCamelCase, '''do_center_crop''' ) ) self.assertTrue(hasattr(lowerCamelCase, '''crop_size''' ) ) def lowercase__ ( self : Any ): '''simple docstring''' lowercase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size, {'''shortest_edge''': 20} ) self.assertEqual(image_processor.crop_size, {'''height''': 18, '''width''': 18} ) lowercase__ = self.image_processing_class.from_dict(self.image_processor_dict, size=42, crop_size=84 ) self.assertEqual(image_processor.size, {'''shortest_edge''': 42} ) self.assertEqual(image_processor.crop_size, {'''height''': 84, '''width''': 84} ) def lowercase__ ( self : Optional[int] ): '''simple docstring''' pass def lowercase__ ( self : Any ): '''simple docstring''' # Initialize image_processing lowercase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images lowercase__ = prepare_image_inputs(self.image_processor_tester, equal_resolution=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase, Image.Image ) # Test not batched input lowercase__ = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ), ) # Test batched lowercase__ = image_processing(lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ), ) def lowercase__ ( self : str ): '''simple docstring''' # Initialize image_processing lowercase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors lowercase__ = prepare_image_inputs(self.image_processor_tester, equal_resolution=lowerCamelCase, numpify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase, np.ndarray ) # Test not batched input lowercase__ = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ), ) # Test batched lowercase__ = image_processing(lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ), ) def lowercase__ ( self : str ): '''simple docstring''' # Initialize image_processing lowercase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors lowercase__ = prepare_image_inputs(self.image_processor_tester, equal_resolution=lowerCamelCase, torchify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase, torch.Tensor ) # Test not batched input lowercase__ = 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.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ), ) # Test batched lowercase__ = image_processing(lowerCamelCase, return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ), )
671
0
'''simple docstring''' from sklearn.metrics import fa_score import datasets __lowercase : Union[str, Any] = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" __lowercase : Any = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n" __lowercase : Dict = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCamelCase ( datasets.Metric ): def __UpperCAmelCase ( self ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] , ) def __UpperCAmelCase ( self , __a , __a , __a=None , __a=1 , __a="binary" , __a=None ): '''simple docstring''' __a : Tuple = fa_score( a__ , a__ , labels=a__ , pos_label=a__ , average=a__ , sample_weight=a__ ) return {"f1": float(a__ ) if score.size == 1 else score}
476
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_albert import AlbertTokenizer else: _lowercase : List[str] = None _lowercase : List[str] = logging.get_logger(__name__) _lowercase : List[Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} _lowercase : str = { "vocab_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/spiece.model", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/spiece.model", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/spiece.model", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/spiece.model", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model", }, "tokenizer_file": { "albert-base-v1": "https://huggingface.co/albert-base-v1/resolve/main/tokenizer.json", "albert-large-v1": "https://huggingface.co/albert-large-v1/resolve/main/tokenizer.json", "albert-xlarge-v1": "https://huggingface.co/albert-xlarge-v1/resolve/main/tokenizer.json", "albert-xxlarge-v1": "https://huggingface.co/albert-xxlarge-v1/resolve/main/tokenizer.json", "albert-base-v2": "https://huggingface.co/albert-base-v2/resolve/main/tokenizer.json", "albert-large-v2": "https://huggingface.co/albert-large-v2/resolve/main/tokenizer.json", "albert-xlarge-v2": "https://huggingface.co/albert-xlarge-v2/resolve/main/tokenizer.json", "albert-xxlarge-v2": "https://huggingface.co/albert-xxlarge-v2/resolve/main/tokenizer.json", }, } _lowercase : List[str] = { "albert-base-v1": 512, "albert-large-v1": 512, "albert-xlarge-v1": 512, "albert-xxlarge-v1": 512, "albert-base-v2": 512, "albert-large-v2": 512, "albert-xlarge-v2": 512, "albert-xxlarge-v2": 512, } _lowercase : Dict = "▁" class _UpperCamelCase ( __snake_case ): """simple docstring""" lowerCAmelCase = VOCAB_FILES_NAMES lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase = AlbertTokenizer def __init__( self , a__=None , a__=None , a__=True , a__=True , a__=False , a__="[CLS]" , a__="[SEP]" , a__="<unk>" , a__="[SEP]" , a__="<pad>" , a__="[CLS]" , a__="[MASK]" , **a__ , ) -> Dict: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. A = ( AddedToken(a__ , lstrip=a__ , rstrip=a__ , normalized=a__ ) if isinstance(a__ , a__ ) else mask_token ) super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , remove_space=a__ , keep_accents=a__ , bos_token=a__ , eos_token=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , **a__ , ) A = do_lower_case A = remove_space A = keep_accents A = vocab_file A = False if not self.vocab_file else True def _UpperCAmelCase ( self , a__ , a__ = None ) -> List[int]: A = [self.sep_token_id] A = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _UpperCAmelCase ( self , a__ , a__ = None ) -> List[int]: A = [self.sep_token_id] A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _UpperCAmelCase ( self , a__ , a__ = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(a__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return A = os.path.join( a__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a__ ): copyfile(self.vocab_file , a__ ) return (out_vocab_file,)
641
0
from __future__ import annotations import inspect import unittest from transformers import ViTConfig 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 TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase_ : def __init__( self , lowercase_ , lowercase_=13 , lowercase_=30 , lowercase_=2 , lowercase_=3 , lowercase_=True , lowercase_=True , lowercase_=32 , lowercase_=2 , lowercase_=4 , lowercase_=37 , lowercase_="gelu" , lowercase_=0.1 , lowercase_=0.1 , lowercase_=10 , lowercase_=0.02 , lowercase_=3 , lowercase_=None , ): _snake_case : Tuple = parent _snake_case : Union[str, Any] = batch_size _snake_case : Optional[int] = image_size _snake_case : Union[str, Any] = patch_size _snake_case : List[str] = num_channels _snake_case : Optional[Any] = is_training _snake_case : str = use_labels _snake_case : Dict = hidden_size _snake_case : Union[str, Any] = num_hidden_layers _snake_case : Tuple = num_attention_heads _snake_case : Dict = intermediate_size _snake_case : Dict = hidden_act _snake_case : Union[str, Any] = hidden_dropout_prob _snake_case : Union[str, Any] = attention_probs_dropout_prob _snake_case : Tuple = type_sequence_label_size _snake_case : int = initializer_range _snake_case : Optional[int] = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _snake_case : Optional[int] = (image_size // patch_size) ** 2 _snake_case : int = 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 : List[Any] = None if self.use_labels: _snake_case : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _snake_case : List[Any] = self.get_config() return config, pixel_values, labels def UpperCamelCase ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowercase_ , initializer_range=self.initializer_range , ) def UpperCamelCase ( self , lowercase_ , lowercase_ , lowercase_ ): _snake_case : List[Any] = TFViTModel(config=lowercase_ ) _snake_case : List[Any] = model(lowercase_ , training=lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. _snake_case : List[Any] = self.image_size // 2 _snake_case : List[str] = pixel_values[:, :, :image_size, :image_size] _snake_case : List[str] = model(lowercase_ , interpolate_pos_encoding=lowercase_ , training=lowercase_ ) _snake_case : Tuple = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def UpperCamelCase ( self , lowercase_ , lowercase_ , lowercase_ ): _snake_case : Tuple = self.type_sequence_label_size _snake_case : Tuple = TFViTForImageClassification(lowercase_ ) _snake_case : List[str] = model(lowercase_ , labels=lowercase_ , training=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. _snake_case : int = self.image_size // 2 _snake_case : Any = pixel_values[:, :, :image_size, :image_size] _snake_case : List[Any] = model(lowercase_ , interpolate_pos_encoding=lowercase_ , training=lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _snake_case : List[str] = 1 _snake_case : Union[str, Any] = TFViTForImageClassification(lowercase_ ) _snake_case : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _snake_case : Any = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCamelCase ( self ): _snake_case : Union[str, Any] = self.prepare_config_and_inputs() _snake_case : str = config_and_inputs _snake_case : Any = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class lowercase_ ( __snake_case , __snake_case , unittest.TestCase ): _lowerCamelCase = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () _lowerCamelCase = ( {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification} if is_tf_available() else {} ) _lowerCamelCase = False _lowerCamelCase = False _lowerCamelCase = False def UpperCamelCase ( self ): _snake_case : str = TFViTModelTester(self ) _snake_case : List[str] = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37 ) def UpperCamelCase ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def UpperCamelCase ( self ): pass @unittest.skip(reason="ViT does not use inputs_embeds" ) def UpperCamelCase ( self ): pass def UpperCamelCase ( self ): _snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : Tuple = model_class(lowercase_ ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) _snake_case : List[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase_ , tf.keras.layers.Layer ) ) def UpperCamelCase ( self ): _snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _snake_case : List[Any] = model_class(lowercase_ ) _snake_case : Optional[int] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _snake_case : str = [*signature.parameters.keys()] _snake_case : List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowercase_ ) def UpperCamelCase ( self ): _snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) def UpperCamelCase ( self ): _snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @slow def UpperCamelCase ( self ): _snake_case : Any = TFViTModel.from_pretrained("google/vit-base-patch16-224" ) self.assertIsNotNone(lowercase_ ) def snake_case () -> str: '''simple docstring''' _snake_case : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class lowercase_ ( unittest.TestCase ): @cached_property def UpperCamelCase ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def UpperCamelCase ( self ): _snake_case : Union[str, Any] = TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ) _snake_case : List[Any] = self.default_image_processor _snake_case : Union[str, Any] = prepare_img() _snake_case : List[Any] = image_processor(images=lowercase_ , return_tensors="tf" ) # forward pass _snake_case : List[Any] = model(**lowercase_ ) # verify the logits _snake_case : Union[str, Any] = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowercase_ ) _snake_case : List[Any] = tf.constant([-0.2_744, 0.8_215, -0.0_836] ) tf.debugging.assert_near(outputs.logits[0, :3] , lowercase_ , atol=1e-4 )
717
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def snake_case (__lowercase , __lowercase=False ) -> List[Any]: '''simple docstring''' try: _snake_case : str = os.environ[key] except KeyError: # KEY isn't set, default to `default`. _snake_case : Union[str, Any] = default else: # KEY is set, convert it to True or False. try: _snake_case : Optional[Any] = strtobool(__lowercase ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F"""If set, {key} must be yes or no.""" ) return _value __SCREAMING_SNAKE_CASE : List[str] = parse_flag_from_env('RUN_SLOW', default=False) def snake_case (__lowercase ) -> Union[str, Any]: '''simple docstring''' return unittest.skip("Test was skipped" )(__lowercase ) def snake_case (__lowercase ) -> Tuple: '''simple docstring''' return unittest.skipUnless(_run_slow_tests , "test is slow" )(__lowercase ) def snake_case (__lowercase ) -> str: '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available() , "test requires only a CPU" )(__lowercase ) def snake_case (__lowercase ) -> Any: '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available() , "test requires a GPU" )(__lowercase ) def snake_case (__lowercase ) -> List[Any]: '''simple docstring''' return unittest.skipUnless(is_xpu_available() , "test requires a XPU" )(__lowercase ) def snake_case (__lowercase ) -> int: '''simple docstring''' return unittest.skipUnless(is_mps_available() , "test requires a `mps` backend support in `torch`" )(__lowercase ) def snake_case (__lowercase ) -> Optional[Any]: '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available() , "test requires the Hugging Face suite" )(__lowercase ) def snake_case (__lowercase ) -> Tuple: '''simple docstring''' return unittest.skipUnless(is_bnb_available() , "test requires the bitsandbytes library" )(__lowercase ) def snake_case (__lowercase ) -> str: '''simple docstring''' return unittest.skipUnless(is_tpu_available() , "test requires TPU" )(__lowercase ) def snake_case (__lowercase ) -> List[Any]: '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1 , "test requires a GPU" )(__lowercase ) def snake_case (__lowercase ) -> int: '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1 , "test requires a XPU" )(__lowercase ) def snake_case (__lowercase ) -> Union[str, Any]: '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1 , "test requires multiple GPUs" )(__lowercase ) def snake_case (__lowercase ) -> List[str]: '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1 , "test requires multiple XPUs" )(__lowercase ) def snake_case (__lowercase ) -> List[Any]: '''simple docstring''' return unittest.skipUnless(is_safetensors_available() , "test requires safetensors" )(__lowercase ) def snake_case (__lowercase ) -> Optional[int]: '''simple docstring''' return unittest.skipUnless(is_deepspeed_available() , "test requires DeepSpeed" )(__lowercase ) def snake_case (__lowercase ) -> List[str]: '''simple docstring''' return unittest.skipUnless(is_torch_version(">=" , "1.12.0" ) , "test requires torch version >= 1.12.0" )(__lowercase ) def snake_case (__lowercase=None , __lowercase=None ) -> int: '''simple docstring''' if test_case is None: return partial(__lowercase , version=__lowercase ) return unittest.skipUnless(is_torch_version(">=" , __lowercase ) , F"""test requires torch version >= {version}""" )(__lowercase ) def snake_case (__lowercase ) -> List[Any]: '''simple docstring''' return unittest.skipUnless(is_tensorboard_available() , "test requires Tensorboard" )(__lowercase ) def snake_case (__lowercase ) -> Any: '''simple docstring''' return unittest.skipUnless(is_wandb_available() , "test requires wandb" )(__lowercase ) def snake_case (__lowercase ) -> Dict: '''simple docstring''' return unittest.skipUnless(is_comet_ml_available() , "test requires comet_ml" )(__lowercase ) __SCREAMING_SNAKE_CASE : Any = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def snake_case (__lowercase ) -> Union[str, Any]: '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available , "test requires at least one tracker to be available and for `comet_ml` to not be installed" , )(__lowercase ) class lowercase_ ( unittest.TestCase ): _lowerCamelCase = True @classmethod def UpperCamelCase ( cls ): _snake_case : List[str] = tempfile.mkdtemp() @classmethod def UpperCamelCase ( cls ): if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def UpperCamelCase ( self ): if self.clear_on_setup: for path in Path(self.tmpdir ).glob("**/*" ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(lowercase_ ) class lowercase_ ( unittest.TestCase ): def UpperCamelCase ( self ): super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class lowercase_ ( unittest.TestCase ): def UpperCamelCase ( self , lowercase_ ): _snake_case : int = mocks if isinstance(lowercase_ , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def snake_case (__lowercase ) -> List[Any]: '''simple docstring''' _snake_case : Tuple = AcceleratorState() _snake_case : str = tensor[None].clone().to(state.device ) _snake_case : List[str] = gather(__lowercase ).cpu() _snake_case : Union[str, Any] = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , __lowercase ): return False return True class lowercase_ : def __init__( self , lowercase_ , lowercase_ , lowercase_ ): _snake_case : Any = returncode _snake_case : List[str] = stdout _snake_case : Tuple = stderr async def snake_case (__lowercase , __lowercase ) -> Tuple: '''simple docstring''' while True: _snake_case : Any = await stream.readline() if line: callback(__lowercase ) else: break async def snake_case (__lowercase , __lowercase=None , __lowercase=None , __lowercase=None , __lowercase=False , __lowercase=False ) -> _RunOutput: '''simple docstring''' if echo: print("\nRunning: " , " ".join(__lowercase ) ) _snake_case : List[str] = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=__lowercase , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=__lowercase , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) _snake_case : int = [] _snake_case : List[str] = [] def tee(__lowercase , __lowercase , __lowercase , __lowercase="" ): _snake_case : Union[str, Any] = line.decode("utf-8" ).rstrip() sink.append(__lowercase ) if not quiet: print(__lowercase , __lowercase , file=__lowercase ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda __lowercase : tee(__lowercase , __lowercase , sys.stdout , label="stdout:" ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda __lowercase : tee(__lowercase , __lowercase , sys.stderr , label="stderr:" ) ) ), ] , timeout=__lowercase , ) return _RunOutput(await p.wait() , __lowercase , __lowercase ) def snake_case (__lowercase , __lowercase=None , __lowercase=None , __lowercase=180 , __lowercase=False , __lowercase=True ) -> _RunOutput: '''simple docstring''' _snake_case : str = asyncio.get_event_loop() _snake_case : Any = loop.run_until_complete( _stream_subprocess(__lowercase , env=__lowercase , stdin=__lowercase , timeout=__lowercase , quiet=__lowercase , echo=__lowercase ) ) _snake_case : Tuple = " ".join(__lowercase ) if result.returncode > 0: _snake_case : List[Any] = "\n".join(result.stderr ) raise RuntimeError( F"""'{cmd_str}' failed with returncode {result.returncode}\n\n""" F"""The combined stderr from workers follows:\n{stderr}""" ) return result class lowercase_ ( __snake_case ): pass def snake_case (__lowercase , __lowercase=False ) -> int: '''simple docstring''' try: _snake_case : int = subprocess.check_output(__lowercase , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(__lowercase , "decode" ): _snake_case : Dict = output.decode("utf-8" ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F"""Command `{' '.join(__lowercase )}` failed with the following error:\n\n{e.output.decode()}""" ) from e
580
0
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("multiplicative_persistence() only accepts integral values" ) if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values" ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) while len(lowerCAmelCase_ ) != 1: __SCREAMING_SNAKE_CASE = [int(lowerCAmelCase_ ) for i in num_string] __SCREAMING_SNAKE_CASE = 1 for i in range(0 , len(lowerCAmelCase_ ) ): total *= numbers[i] __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) steps += 1 return steps def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("additive_persistence() only accepts integral values" ) if num < 0: raise ValueError("additive_persistence() does not accept negative values" ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) while len(lowerCAmelCase_ ) != 1: __SCREAMING_SNAKE_CASE = [int(lowerCAmelCase_ ) for i in num_string] __SCREAMING_SNAKE_CASE = 0 for i in range(0 , len(lowerCAmelCase_ ) ): total += numbers[i] __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
'''simple docstring''' import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowercase__ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.31.0") require_version("datasets>=1.14.0", "To fix: pip install -r examples/pytorch/audio-classification/requirements.txt") def __UpperCamelCase ( __lowerCamelCase : np.ndarray , __lowerCamelCase : float , __lowerCamelCase : int = 1_6000 ) -> Optional[int]: '''simple docstring''' _a = int(round(sample_rate * max_length ) ) if len(__lowerCamelCase ) <= sample_length: return wav _a = randint(0 , len(__lowerCamelCase ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class __SCREAMING_SNAKE_CASE : UpperCAmelCase = field(default=lowerCamelCase__ , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''A file containing the training audio paths and labels.'''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''A file containing the validation audio paths and labels.'''} ) UpperCAmelCase = field( default='''train''' , metadata={ '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\'''' } , ) UpperCAmelCase = field( default='''validation''' , metadata={ '''help''': ( '''The name of the training data set split to use (via the datasets library). Defaults to \'validation\'''' ) } , ) UpperCAmelCase = field( default='''audio''' , metadata={'''help''': '''The name of the dataset column containing the audio data. Defaults to \'audio\''''} , ) UpperCAmelCase = field( default='''label''' , metadata={'''help''': '''The name of the dataset column containing the labels. Defaults to \'label\''''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) UpperCAmelCase = field( default=20 , metadata={'''help''': '''Audio clips will be randomly cut to this length during training if the value is set.'''} , ) @dataclass class __SCREAMING_SNAKE_CASE : UpperCAmelCase = field( default='''facebook/wav2vec2-base''' , metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} , ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from the Hub'''} ) UpperCAmelCase = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Name or path of preprocessor config.'''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Whether to freeze the feature encoder layers of the model.'''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Whether to generate an attention mask in the feature extractor.'''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''} ) UpperCAmelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''} , ) def a_ ( self ) -> List[Any]: if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( "The argument `--freeze_feature_extractor` is deprecated and " "will be removed in a future version. Use `--freeze_feature_encoder`" "instead. Setting `freeze_feature_encoder==True`." , __UpperCamelCase , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( "The argument `--freeze_feature_extractor` is deprecated and " "should not be used in combination with `--freeze_feature_encoder`." "Only make use of `--freeze_feature_encoder`." ) def __UpperCamelCase ( ) -> Dict: '''simple docstring''' _a = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _a , _a , _a = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _a , _a , _a = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_audio_classification" , __lowerCamelCase , __lowerCamelCase ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _a = training_args.get_process_log_level() logger.setLevel(__lowerCamelCase ) transformers.utils.logging.set_verbosity(__lowerCamelCase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu} " + F"distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}" ) logger.info(F"Training/evaluation parameters {training_args}" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. _a = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _a = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to train from scratch." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Initialize our dataset and prepare it for the audio classification task. _a = DatasetDict() _a = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) _a = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( F"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. " "Make sure to set `--audio_column_name` to the correct audio column - one of " F"{', '.join(raw_datasets['train'].column_names )}." ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( F"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. " "Make sure to set `--label_column_name` to the correct text column - one of " F"{', '.join(raw_datasets['train'].column_names )}." ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy _a = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. _a = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) _a = feature_extractor.model_input_names[0] def train_transforms(__lowerCamelCase : Dict ): _a = [] for audio in batch[data_args.audio_column_name]: _a = random_subsample( audio["array"] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(__lowerCamelCase ) _a = feature_extractor(__lowerCamelCase , sampling_rate=feature_extractor.sampling_rate ) _a = {model_input_name: inputs.get(__lowerCamelCase )} _a = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(__lowerCamelCase : List[Any] ): _a = [audio["array"] for audio in batch[data_args.audio_column_name]] _a = feature_extractor(__lowerCamelCase , sampling_rate=feature_extractor.sampling_rate ) _a = {model_input_name: inputs.get(__lowerCamelCase )} _a = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. _a = raw_datasets["train"].features[data_args.label_column_name].names _a , _a = {}, {} for i, label in enumerate(__lowerCamelCase ): _a = str(__lowerCamelCase ) _a = label # Load the accuracy metric from the datasets package _a = evaluate.load("accuracy" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(__lowerCamelCase : Dict ): _a = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=__lowerCamelCase , references=eval_pred.label_ids ) _a = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(__lowerCamelCase ) , labelaid=__lowerCamelCase , idalabel=__lowerCamelCase , finetuning_task="audio-classification" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) _a = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=__lowerCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: _a = ( raw_datasets["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(__lowerCamelCase , output_all_columns=__lowerCamelCase ) if training_args.do_eval: if data_args.max_eval_samples is not None: _a = ( raw_datasets["eval"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(__lowerCamelCase , output_all_columns=__lowerCamelCase ) # Initialize our trainer _a = Trainer( model=__lowerCamelCase , args=__lowerCamelCase , train_dataset=raw_datasets["train"] if training_args.do_train else None , eval_dataset=raw_datasets["eval"] if training_args.do_eval else None , compute_metrics=__lowerCamelCase , tokenizer=__lowerCamelCase , ) # Training if training_args.do_train: _a = None if training_args.resume_from_checkpoint is not None: _a = training_args.resume_from_checkpoint elif last_checkpoint is not None: _a = last_checkpoint _a = trainer.train(resume_from_checkpoint=__lowerCamelCase ) trainer.save_model() trainer.log_metrics("train" , train_result.metrics ) trainer.save_metrics("train" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _a = trainer.evaluate() trainer.log_metrics("eval" , __lowerCamelCase ) trainer.save_metrics("eval" , __lowerCamelCase ) # Write model card and (optionally) push to hub _a = { "finetuned_from": model_args.model_name_or_path, "tasks": "audio-classification", "dataset": data_args.dataset_name, "tags": ["audio-classification"], } if training_args.push_to_hub: trainer.push_to_hub(**__lowerCamelCase ) else: trainer.create_model_card(**__lowerCamelCase ) if __name__ == "__main__": main()
715
'''simple docstring''' class __SCREAMING_SNAKE_CASE : def __init__( self , __UpperCamelCase ) -> Optional[Any]: # we need a list not a string, so do something to change the type _a = arr.split("," ) def a_ ( self ) -> List[Any]: _a = [int(self.array[0] )] * len(self.array ) _a = [int(self.array[0] )] * len(self.array ) for i in range(1 , len(self.array ) ): _a = max( int(self.array[i] ) + sum_value[i - 1] , int(self.array[i] ) ) _a = max(sum_value[i] , rear[i - 1] ) return rear[len(self.array ) - 1] if __name__ == "__main__": lowercase__ = input("please input some numbers:") lowercase__ = SubArray(whole_array) lowercase__ = array.solve_sub_array() print(("the results is:", re))
276
0
from math import factorial _UpperCAmelCase = {str(digit): factorial(digit) for digit in range(10)} def __UpperCamelCase (lowerCAmelCase : int ) -> int: if not isinstance(lowerCAmelCase, lowerCAmelCase ): raise TypeError('Parameter number must be int' ) if number < 0: raise ValueError('Parameter number must be greater than or equal to 0' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(lowerCAmelCase ) ) def __UpperCamelCase (lowerCAmelCase : int = 60, lowerCAmelCase : int = 1_000_000 ) -> int: if not isinstance(lowerCAmelCase, lowerCAmelCase ) or not isinstance(lowerCAmelCase, lowerCAmelCase ): raise TypeError('Parameters chain_length and number_limit must be int' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( 'Parameters chain_length and number_limit must be greater than 0' ) # the counter for the chains with the exact desired length A = 0 # the cached sizes of the previous chains A = {} for start_chain_element in range(1, lowerCAmelCase ): # The temporary set will contain the elements of the chain A = set() A = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. A = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(lowerCAmelCase ) chain_set_length += 1 A = digit_factorial_sum(lowerCAmelCase ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] A = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'''{solution()}''')
699
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _UpperCAmelCase ( __lowercase ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = ['''image_processor''', '''tokenizer'''] SCREAMING_SNAKE_CASE : List[str] = '''BridgeTowerImageProcessor''' SCREAMING_SNAKE_CASE : Tuple = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Optional[int] ): super().__init__(UpperCamelCase__ , UpperCamelCase__ ) def __call__( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[bool, str, PaddingStrategy] = False , UpperCamelCase__ : Union[bool, str, TruncationStrategy] = None , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : int = 0 , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , **UpperCamelCase__ : List[Any] , ): A = self.tokenizer( text=UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ , stride=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_token_type_ids=UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , return_overflowing_tokens=UpperCamelCase__ , return_special_tokens_mask=UpperCamelCase__ , return_offsets_mapping=UpperCamelCase__ , return_length=UpperCamelCase__ , verbose=UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ , ) # add pixel_values + pixel_mask A = self.image_processor( UpperCamelCase__ , return_tensors=UpperCamelCase__ , do_normalize=UpperCamelCase__ , do_center_crop=UpperCamelCase__ , **UpperCamelCase__ ) encoding.update(UpperCamelCase__ ) return encoding def UpperCamelCase ( self : Dict , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Any ): return self.tokenizer.batch_decode(*UpperCamelCase__ , **UpperCamelCase__ ) def UpperCamelCase ( self : int , *UpperCamelCase__ : int , **UpperCamelCase__ : List[str] ): return self.tokenizer.decode(*UpperCamelCase__ , **UpperCamelCase__ ) @property def UpperCamelCase ( self : Any ): A = self.tokenizer.model_input_names A = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
699
1
"""simple docstring""" SCREAMING_SNAKE_CASE = {str(digit): digit**5 for digit in range(10)} def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" return sum(DIGITS_FIFTH_POWER[digit] for digit in str(lowerCAmelCase__ ) ) def __lowerCAmelCase( ): """simple docstring""" return sum( number for number in range(1_000 ,1_000_000 ) if number == digits_fifth_powers_sum(lowerCAmelCase__ ) ) if __name__ == "__main__": print(solution())
721
"""simple docstring""" import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration SCREAMING_SNAKE_CASE = pytest.mark.integration SCREAMING_SNAKE_CASE = {'comet'} SCREAMING_SNAKE_CASE = importlib.util.find_spec('fairseq') is not None SCREAMING_SNAKE_CASE = {'code_eval'} SCREAMING_SNAKE_CASE = os.name == 'nt' SCREAMING_SNAKE_CASE = {'bertscore', 'frugalscore', 'perplexity'} SCREAMING_SNAKE_CASE = importlib.util.find_spec('transformers') is not None def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" @wraps(__UpperCAmelCase ) def wrapper(self ,__UpperCAmelCase ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self ,__UpperCAmelCase ) return wrapper def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" @wraps(__UpperCAmelCase ) def wrapper(self ,__UpperCAmelCase ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self ,__UpperCAmelCase ) return wrapper def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" @wraps(__UpperCAmelCase ) def wrapper(self ,__UpperCAmelCase ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self ,__UpperCAmelCase ) return wrapper def __lowerCAmelCase( ): """simple docstring""" _lowercase : int = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) @local class _lowerCamelCase (parameterized.TestCase ): _snake_case = {} _snake_case = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning' ) def __UpperCAmelCase ( self : str , lowerCamelCase_ : List[str] ): """simple docstring""" _lowercase : Optional[Any] = '[...]' _lowercase : str = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , lowerCamelCase_ ) ).module_path ) _lowercase : Dict = datasets.load.import_main_class(metric_module.__name__ , dataset=lowerCamelCase_ ) # check parameters _lowercase : Optional[int] = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(lowerCamelCase_ , metric_module.__name__ ): with self.use_local_metrics(): try: _lowercase : Optional[Any] = doctest.testmod(lowerCamelCase_ , verbose=lowerCamelCase_ , raise_on_error=lowerCamelCase_ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __UpperCAmelCase ( self : Any , lowerCamelCase_ : Dict ): """simple docstring""" _lowercase : Optional[Any] = '[...]' _lowercase : Dict = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , lowerCamelCase_ ) ).module_path ) # run doctest with self.use_local_metrics(): _lowercase : str = doctest.testmod(lowerCamelCase_ , verbose=lowerCamelCase_ , raise_on_error=lowerCamelCase_ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __UpperCAmelCase ( self : Tuple , lowerCamelCase_ : int , lowerCamelCase_ : str ): """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](lowerCamelCase_ ): yield else: yield @contextmanager def __UpperCAmelCase ( self : Dict ): """simple docstring""" def load_local_metric(lowerCamelCase_ : Optional[Any] , *lowerCamelCase_ : Any , **lowerCamelCase_ : Optional[int] ): return load_metric(os.path.join('metrics' , lowerCamelCase_ ) , *lowerCamelCase_ , **lowerCamelCase_ ) with patch('datasets.load_metric' ) as mock_load_metric: _lowercase : str = load_local_metric yield @classmethod def __UpperCAmelCase ( cls : Tuple , lowerCamelCase_ : Tuple ): """simple docstring""" def wrapper(lowerCamelCase_ : int ): _lowercase : Any = contextmanager(lowerCamelCase_ ) _lowercase : Any = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' ,'' ,'' ) # handle pytest cli flags class _lowerCamelCase (__lowerCamelCase ): def __UpperCAmelCase ( self : Optional[Any] , lowerCamelCase_ : str ): """simple docstring""" assert len(input_dict['input_ids'] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: _lowercase : Dict = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" import torch def bert_cos_score_idf(__UpperCAmelCase ,__UpperCAmelCase ,*__UpperCAmelCase ,**__UpperCAmelCase ): return torch.tensor([[1.0, 1.0, 1.0]] * len(__UpperCAmelCase ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: _lowercase : Tuple = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def __lowerCAmelCase( __UpperCAmelCase ): """simple docstring""" def load_from_checkpoint(__UpperCAmelCase ): class _lowerCamelCase : def __UpperCAmelCase ( self : Tuple , lowerCamelCase_ : str , *lowerCamelCase_ : List[Any] , **lowerCamelCase_ : List[str] ): """simple docstring""" assert len(lowerCamelCase_ ) == 2 _lowercase : Union[str, Any] = [0.19, 0.92] return scores, sum(lowerCamelCase_ ) / len(lowerCamelCase_ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: _lowercase : Dict = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: _lowercase : str = load_from_checkpoint yield def __lowerCAmelCase( ): """simple docstring""" _lowercase : Tuple = load_metric(os.path.join('metrics' ,'seqeval' ) ) _lowercase : int = 'ERROR' _lowercase : Union[str, Any] = F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(__UpperCAmelCase ,match=re.escape(__UpperCAmelCase ) ): metric.compute(predictions=[] ,references=[] ,scheme=__UpperCAmelCase )
283
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCamelCase__ : Any = { '''configuration_convbert''': ['''CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConvBertConfig''', '''ConvBertOnnxConfig'''], '''tokenization_convbert''': ['''ConvBertTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Any = ['''ConvBertTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : Dict = [ '''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: UpperCamelCase__ : int = [ '''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 UpperCamelCase__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
578
'''simple docstring''' from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCAmelCase_ ( _lowerCamelCase: str , _lowerCamelCase: float | Decimal , _lowerCamelCase: float = 10**-10 ): __SCREAMING_SNAKE_CASE : List[Any] = a while True: __SCREAMING_SNAKE_CASE : Optional[Any] = Decimal(_lowerCamelCase ) - ( Decimal(eval(_lowerCamelCase ) ) / Decimal(eval(str(diff(_lowerCamelCase ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(_lowerCamelCase ) ) < precision: # noqa: S307 return float(_lowerCamelCase ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") # Find root of polynomial print(f"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}") # Find Square Root of 5 print(f"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}") # Exponential Roots print(f"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")
578
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase__ : List[str] = { "configuration_mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig", "MegaOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Optional[Any] = [ "MEGA_PRETRAINED_MODEL_ARCHIVE_LIST", "MegaForCausalLM", "MegaForMaskedLM", "MegaForMultipleChoice", "MegaForQuestionAnswering", "MegaForSequenceClassification", "MegaForTokenClassification", "MegaModel", "MegaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mega import ( MEGA_PRETRAINED_MODEL_ARCHIVE_LIST, MegaForCausalLM, MegaForMaskedLM, MegaForMultipleChoice, MegaForQuestionAnswering, MegaForSequenceClassification, MegaForTokenClassification, MegaModel, MegaPreTrainedModel, ) else: import sys lowercase__ : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
704
from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase__ : Tuple = logging.get_logger(__name__) lowercase__ : Union[str, Any] = { "speechbrain/m-ctc-t-large": "https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class SCREAMING_SNAKE_CASE__ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" _snake_case = 'mctct' def __init__( self , SCREAMING_SNAKE_CASE_=8065 , SCREAMING_SNAKE_CASE_=1536 , SCREAMING_SNAKE_CASE_=36 , SCREAMING_SNAKE_CASE_=6144 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=384 , SCREAMING_SNAKE_CASE_=920 , SCREAMING_SNAKE_CASE_=1E-5 , SCREAMING_SNAKE_CASE_=0.3 , SCREAMING_SNAKE_CASE_="relu" , SCREAMING_SNAKE_CASE_=0.0_2 , SCREAMING_SNAKE_CASE_=0.3 , SCREAMING_SNAKE_CASE_=0.3 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0.3 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=(7,) , SCREAMING_SNAKE_CASE_=(3,) , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="sum" , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , )-> Tuple: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = intermediate_size __UpperCamelCase = num_attention_heads __UpperCamelCase = attention_head_dim __UpperCamelCase = max_position_embeddings __UpperCamelCase = layer_norm_eps __UpperCamelCase = layerdrop __UpperCamelCase = hidden_act __UpperCamelCase = initializer_range __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = pad_token_id __UpperCamelCase = bos_token_id __UpperCamelCase = eos_token_id __UpperCamelCase = conv_glu_dim __UpperCamelCase = conv_dropout __UpperCamelCase = num_conv_layers __UpperCamelCase = input_feat_per_channel __UpperCamelCase = input_channels __UpperCamelCase = conv_channels __UpperCamelCase = ctc_loss_reduction __UpperCamelCase = ctc_zero_infinity # prevents config testing fail with exporting to json __UpperCamelCase = list(SCREAMING_SNAKE_CASE_ ) __UpperCamelCase = list(SCREAMING_SNAKE_CASE_ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( '''Configuration for convolutional module is incorrect. ''' '''It is required that `len(config.conv_kernel)` == `config.num_conv_layers` ''' F"but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, " F"`config.num_conv_layers = {self.num_conv_layers}`." )
451
0
from manim import * class lowercase ( A__ ): '''simple docstring''' def snake_case_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = Rectangle(height=0.5 , width=0.5 ) UpperCAmelCase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 ) UpperCAmelCase = Rectangle(height=0.25 , width=0.25 ) UpperCAmelCase = [mem.copy() for i in range(6 )] UpperCAmelCase = [mem.copy() for i in range(6 )] UpperCAmelCase = VGroup(*_snake_case ).arrange(_snake_case , buff=0 ) UpperCAmelCase = VGroup(*_snake_case ).arrange(_snake_case , buff=0 ) UpperCAmelCase = VGroup(_snake_case , _snake_case ).arrange(_snake_case , buff=0 ) UpperCAmelCase = Text('''CPU''' , font_size=24 ) UpperCAmelCase = Group(_snake_case , _snake_case ).arrange(_snake_case , buff=0.5 , aligned_edge=_snake_case ) cpu.move_to([-2.5, -0.5, 0] ) self.add(_snake_case ) UpperCAmelCase = [mem.copy() for i in range(4 )] UpperCAmelCase = VGroup(*_snake_case ).arrange(_snake_case , buff=0 ) UpperCAmelCase = Text('''GPU''' , font_size=24 ) UpperCAmelCase = Group(_snake_case , _snake_case ).arrange(_snake_case , buff=0.5 , aligned_edge=_snake_case ) gpu.move_to([-1, -1, 0] ) self.add(_snake_case ) UpperCAmelCase = [mem.copy() for i in range(6 )] UpperCAmelCase = VGroup(*_snake_case ).arrange(_snake_case , buff=0 ) UpperCAmelCase = Text('''Model''' , font_size=24 ) UpperCAmelCase = Group(_snake_case , _snake_case ).arrange(_snake_case , buff=0.5 , aligned_edge=_snake_case ) model.move_to([3, -1.0, 0] ) self.add(_snake_case ) UpperCAmelCase = [] UpperCAmelCase = [] for i, rect in enumerate(_snake_case ): UpperCAmelCase = fill.copy().set_fill(_snake_case , opacity=0.8 ) target.move_to(_snake_case ) model_arr.append(_snake_case ) UpperCAmelCase = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0.0 ).set_fill(_snake_case , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(_snake_case ) self.add(*_snake_case , *_snake_case ) UpperCAmelCase = [meta_mem.copy() for i in range(6 )] UpperCAmelCase = [meta_mem.copy() for i in range(6 )] UpperCAmelCase = VGroup(*_snake_case ).arrange(_snake_case , buff=0 ) UpperCAmelCase = VGroup(*_snake_case ).arrange(_snake_case , buff=0 ) UpperCAmelCase = VGroup(_snake_case , _snake_case ).arrange(_snake_case , buff=0 ) UpperCAmelCase = Text('''Disk''' , font_size=24 ) UpperCAmelCase = Group(_snake_case , _snake_case ).arrange(_snake_case , buff=0.5 , aligned_edge=_snake_case ) disk.move_to([-4, -1.25, 0] ) self.add(_snake_case , _snake_case ) UpperCAmelCase = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) UpperCAmelCase = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(_snake_case , _snake_case ) UpperCAmelCase = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(_snake_case , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(_snake_case ) UpperCAmelCase = MarkupText( f"""Now watch as an input is passed through the model\nand how the memory is utilized and handled.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_snake_case ) ) UpperCAmelCase = Square(0.3 ) input.set_fill(_snake_case , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , _snake_case , buff=0.5 ) self.play(Write(_snake_case ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=_snake_case , buff=0.02 ) self.play(MoveToTarget(_snake_case ) ) self.play(FadeOut(_snake_case ) ) UpperCAmelCase = Arrow(start=_snake_case , end=_snake_case , color=_snake_case , buff=0.5 ) a.next_to(model_arr[0].get_left() , _snake_case , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) UpperCAmelCase = MarkupText( f"""As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(_snake_case , run_time=3 ) ) UpperCAmelCase = {'''run_time''': 1, '''fade_in''': True, '''fade_out''': True, '''buff''': 0.02} self.play( Write(_snake_case ) , Circumscribe(model_arr[0] , color=_snake_case , **_snake_case ) , Circumscribe(model_cpu_arr[0] , color=_snake_case , **_snake_case ) , Circumscribe(gpu_rect[0] , color=_snake_case , **_snake_case ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) UpperCAmelCase = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 , _snake_case , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) UpperCAmelCase = AnimationGroup( FadeOut(_snake_case , run_time=0.5 ) , MoveToTarget(_snake_case , run_time=0.5 ) , FadeIn(_snake_case , run_time=0.5 ) , lag_ratio=0.2 ) self.play(_snake_case ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: UpperCAmelCase = 0.7 self.play( Circumscribe(model_arr[i] , **_snake_case ) , Circumscribe(cpu_left_col_base[i] , **_snake_case ) , Circumscribe(cpu_left_col_base[i + 1] , color=_snake_case , **_snake_case ) , Circumscribe(gpu_rect[0] , color=_snake_case , **_snake_case ) , Circumscribe(model_arr[i + 1] , color=_snake_case , **_snake_case ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.02 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=_snake_case , **_snake_case ) , Circumscribe(cpu_left_col_base[-1] , color=_snake_case , **_snake_case ) , Circumscribe(gpu_rect[0] , color=_snake_case , **_snake_case ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) UpperCAmelCase = a_c UpperCAmelCase = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.02 , buff=0.5 ) self.play( FadeOut(_snake_case ) , FadeOut(_snake_case , run_time=0.5 ) , ) UpperCAmelCase = MarkupText(f"""Inference on a model too large for GPU memory\nis successfully completed.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(_snake_case , run_time=3 ) , MoveToTarget(_snake_case ) ) self.wait()
254
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class lowercase ( A__ , A__ , A__ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [R"""h\.\d+\.attn\.bias""", R"""h\.\d+\.attn\.masked_bias"""] @register_to_config def __init__( self , _snake_case , _snake_case , _snake_case = None , _snake_case = 5_0257 , _snake_case = 1024 , _snake_case = 768 , _snake_case = 12 , _snake_case = 12 , _snake_case = None , _snake_case = "gelu_new" , _snake_case = 0.1 , _snake_case = 0.1 , _snake_case = 0.1 , _snake_case = 1e-5 , _snake_case = 0.02 , _snake_case = True , _snake_case = True , _snake_case = False , _snake_case = False , ) -> Any: """simple docstring""" super().__init__() UpperCAmelCase = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and""" f""" `n_embd`: {n_embd} are not equal.""" ) UpperCAmelCase = prefix_inner_dim UpperCAmelCase = prefix_hidden_dim UpperCAmelCase = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) UpperCAmelCase = ( nn.Linear(self.prefix_hidden_dim , _snake_case ) if self.prefix_hidden_dim is not None else nn.Identity() ) UpperCAmelCase = GPTaConfig( vocab_size=_snake_case , n_positions=_snake_case , n_embd=_snake_case , n_layer=_snake_case , n_head=_snake_case , n_inner=_snake_case , activation_function=_snake_case , resid_pdrop=_snake_case , embd_pdrop=_snake_case , attn_pdrop=_snake_case , layer_norm_epsilon=_snake_case , initializer_range=_snake_case , scale_attn_weights=_snake_case , use_cache=_snake_case , scale_attn_by_inverse_layer_idx=_snake_case , reorder_and_upcast_attn=_snake_case , ) UpperCAmelCase = GPTaLMHeadModel(_snake_case ) def snake_case_ ( self , _snake_case , _snake_case , _snake_case = None , _snake_case = None , ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.transformer.transformer.wte(_snake_case ) UpperCAmelCase = self.encode_prefix(_snake_case ) UpperCAmelCase = self.decode_prefix(_snake_case ) UpperCAmelCase = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: UpperCAmelCase = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) UpperCAmelCase = torch.cat((dummy_token, input_ids) , dim=1 ) UpperCAmelCase = self.transformer(inputs_embeds=_snake_case , labels=_snake_case , attention_mask=_snake_case ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def snake_case_ ( self , _snake_case , _snake_case ) -> torch.Tensor: """simple docstring""" return torch.zeros(_snake_case , self.prefix_length , dtype=torch.intaa , device=_snake_case ) def snake_case_ ( self , _snake_case ) -> Union[str, Any]: """simple docstring""" return self.encode_prefix(_snake_case ) @torch.no_grad() def snake_case_ ( self , _snake_case , _snake_case , _snake_case ) -> Tuple: """simple docstring""" UpperCAmelCase = torch.split(_snake_case , 1 , dim=0 ) UpperCAmelCase = [] UpperCAmelCase = [] for feature in features: UpperCAmelCase = self.decode_prefix(feature.to(_snake_case ) ) # back to the clip feature # Only support beam search for now UpperCAmelCase , UpperCAmelCase = self.generate_beam( input_embeds=_snake_case , device=_snake_case , eos_token_id=_snake_case ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) UpperCAmelCase = torch.stack(_snake_case ) UpperCAmelCase = torch.stack(_snake_case ) return generated_tokens, generated_seq_lengths @torch.no_grad() def snake_case_ ( self , _snake_case=None , _snake_case=None , _snake_case=None , _snake_case = 5 , _snake_case = 67 , _snake_case = 1.0 , _snake_case = None , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = eos_token_id UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = torch.ones(_snake_case , device=_snake_case , dtype=torch.int ) UpperCAmelCase = torch.zeros(_snake_case , device=_snake_case , dtype=torch.bool ) if input_embeds is not None: UpperCAmelCase = input_embeds else: UpperCAmelCase = self.transformer.transformer.wte(_snake_case ) for i in range(_snake_case ): UpperCAmelCase = self.transformer(inputs_embeds=_snake_case ) UpperCAmelCase = outputs.logits UpperCAmelCase = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) UpperCAmelCase = logits.softmax(-1 ).log() if scores is None: UpperCAmelCase , UpperCAmelCase = logits.topk(_snake_case , -1 ) UpperCAmelCase = generated.expand(_snake_case , *generated.shape[1:] ) UpperCAmelCase , UpperCAmelCase = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: UpperCAmelCase = next_tokens else: UpperCAmelCase = tokens.expand(_snake_case , *tokens.shape[1:] ) UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) else: UpperCAmelCase = -float(np.inf ) UpperCAmelCase = 0 UpperCAmelCase = scores[:, None] + logits seq_lengths[~is_stopped] += 1 UpperCAmelCase = scores_sum / seq_lengths[:, None] UpperCAmelCase , UpperCAmelCase = scores_sum_average.view(-1 ).topk(_snake_case , -1 ) UpperCAmelCase = next_tokens // scores_sum.shape[1] UpperCAmelCase = seq_lengths[next_tokens_source] UpperCAmelCase = next_tokens % scores_sum.shape[1] UpperCAmelCase = next_tokens.unsqueeze(1 ) UpperCAmelCase = tokens[next_tokens_source] UpperCAmelCase = torch.cat((tokens, next_tokens) , dim=1 ) UpperCAmelCase = generated[next_tokens_source] UpperCAmelCase = scores_sum_average * seq_lengths UpperCAmelCase = is_stopped[next_tokens_source] UpperCAmelCase = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) UpperCAmelCase = torch.cat((generated, next_token_embed) , dim=1 ) UpperCAmelCase = is_stopped + next_tokens.eq(_snake_case ).squeeze() if is_stopped.all(): break UpperCAmelCase = scores / seq_lengths UpperCAmelCase = scores.argsort(descending=_snake_case ) # tokens tensors are already padded to max_seq_length UpperCAmelCase = [tokens[i] for i in order] UpperCAmelCase = torch.stack(_snake_case , dim=0 ) UpperCAmelCase = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
254
1
def _SCREAMING_SNAKE_CASE ( lowercase : int = 50 ): '''simple docstring''' lowerCamelCase_ = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(F"""{solution() = }""")
706
import unittest from transformers import ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_tf, require_torch, require_torch_gpu, require_torch_or_tf, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class A( unittest.TestCase ): '''simple docstring''' UpperCamelCase = MODEL_FOR_CAUSAL_LM_MAPPING UpperCamelCase = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def a__ ( self : Any ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ = pipeline(task='text-generation' , model='sshleifer/tiny-ctrl' , framework='pt' ) # Using `do_sample=False` to force deterministic output lowerCamelCase_ = text_generator('This is a test' , do_sample=A_ ) self.assertEqual( A_ , [ { 'generated_text': ( 'This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.' ' oscope. FiliFili@@' ) } ] , ) lowerCamelCase_ = text_generator(['This is a test', 'This is a second test'] ) self.assertEqual( A_ , [ [ { 'generated_text': ( 'This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.' ' oscope. FiliFili@@' ) } ], [ { 'generated_text': ( 'This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy' ' oscope. oscope. FiliFili@@' ) } ], ] , ) lowerCamelCase_ = text_generator('This is a test' , do_sample=A_ , num_return_sequences=2 , return_tensors=A_ ) self.assertEqual( A_ , [ {'generated_token_ids': ANY(A_ )}, {'generated_token_ids': ANY(A_ )}, ] , ) lowerCamelCase_ = text_generator.model.config.eos_token_id lowerCamelCase_ = '<pad>' lowerCamelCase_ = text_generator( ['This is a test', 'This is a second test'] , do_sample=A_ , num_return_sequences=2 , batch_size=2 , return_tensors=A_ , ) self.assertEqual( A_ , [ [ {'generated_token_ids': ANY(A_ )}, {'generated_token_ids': ANY(A_ )}, ], [ {'generated_token_ids': ANY(A_ )}, {'generated_token_ids': ANY(A_ )}, ], ] , ) @require_tf def a__ ( self : Optional[int] ) -> str: """simple docstring""" lowerCamelCase_ = pipeline(task='text-generation' , model='sshleifer/tiny-ctrl' , framework='tf' ) # Using `do_sample=False` to force deterministic output lowerCamelCase_ = text_generator('This is a test' , do_sample=A_ ) self.assertEqual( A_ , [ { 'generated_text': ( 'This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵' ' please,' ) } ] , ) lowerCamelCase_ = text_generator(['This is a test', 'This is a second test'] , do_sample=A_ ) self.assertEqual( A_ , [ [ { 'generated_text': ( 'This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵' ' please,' ) } ], [ { 'generated_text': ( 'This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes' ' Cannes 閲閲Cannes Cannes Cannes 攵 please,' ) } ], ] , ) def a__ ( self : Optional[int] , A_ : Dict , A_ : int , A_ : List[str] ) -> str: """simple docstring""" lowerCamelCase_ = TextGenerationPipeline(model=A_ , tokenizer=A_ ) return text_generator, ["This is a test", "Another test"] def a__ ( self : Dict ) -> str: """simple docstring""" lowerCamelCase_ = 'Hello I believe in' lowerCamelCase_ = pipeline('text-generation' , model='hf-internal-testing/tiny-random-gpt2' ) lowerCamelCase_ = text_generator(A_ ) self.assertEqual( A_ , [{'generated_text': 'Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'}] , ) lowerCamelCase_ = text_generator(A_ , stop_sequence=' fe' ) self.assertEqual(A_ , [{'generated_text': 'Hello I believe in fe'}] ) def a__ ( self : Any , A_ : Optional[Any] , A_ : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ = text_generator.model lowerCamelCase_ = text_generator.tokenizer lowerCamelCase_ = text_generator('This is a test' ) self.assertEqual(A_ , [{'generated_text': ANY(A_ )}] ) self.assertTrue(outputs[0]['generated_text'].startswith('This is a test' ) ) lowerCamelCase_ = text_generator('This is a test' , return_full_text=A_ ) self.assertEqual(A_ , [{'generated_text': ANY(A_ )}] ) self.assertNotIn('This is a test' , outputs[0]['generated_text'] ) lowerCamelCase_ = pipeline(task='text-generation' , model=A_ , tokenizer=A_ , return_full_text=A_ ) lowerCamelCase_ = text_generator('This is a test' ) self.assertEqual(A_ , [{'generated_text': ANY(A_ )}] ) self.assertNotIn('This is a test' , outputs[0]['generated_text'] ) lowerCamelCase_ = text_generator('This is a test' , return_full_text=A_ ) self.assertEqual(A_ , [{'generated_text': ANY(A_ )}] ) self.assertTrue(outputs[0]['generated_text'].startswith('This is a test' ) ) lowerCamelCase_ = text_generator(['This is great !', 'Something else'] , num_return_sequences=2 , do_sample=A_ ) self.assertEqual( A_ , [ [{'generated_text': ANY(A_ )}, {'generated_text': ANY(A_ )}], [{'generated_text': ANY(A_ )}, {'generated_text': ANY(A_ )}], ] , ) if text_generator.tokenizer.pad_token is not None: lowerCamelCase_ = text_generator( ['This is great !', 'Something else'] , num_return_sequences=2 , batch_size=2 , do_sample=A_ ) self.assertEqual( A_ , [ [{'generated_text': ANY(A_ )}, {'generated_text': ANY(A_ )}], [{'generated_text': ANY(A_ )}, {'generated_text': ANY(A_ )}], ] , ) with self.assertRaises(A_ ): lowerCamelCase_ = text_generator('test' , return_full_text=A_ , return_text=A_ ) with self.assertRaises(A_ ): lowerCamelCase_ = text_generator('test' , return_full_text=A_ , return_tensors=A_ ) with self.assertRaises(A_ ): lowerCamelCase_ = text_generator('test' , return_text=A_ , return_tensors=A_ ) # Empty prompt is slighly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): lowerCamelCase_ = text_generator('' ) self.assertEqual(A_ , [{'generated_text': ANY(A_ )}] ) else: with self.assertRaises((ValueError, AssertionError) ): lowerCamelCase_ = text_generator('' ) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. return # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. lowerCamelCase_ = ['RwkvForCausalLM', 'XGLMForCausalLM', 'GPTNeoXForCausalLM'] if ( tokenizer.model_max_length < 10000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ): text_generator('This is a test' * 500 , max_new_tokens=20 ) lowerCamelCase_ = text_generator('This is a test' * 500 , handle_long_generation='hole' , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(A_ ): text_generator( 'This is a test' * 500 , handle_long_generation='hole' , max_new_tokens=tokenizer.model_max_length + 10 , ) @require_torch @require_accelerate @require_torch_gpu def a__ ( self : Union[str, Any] ) -> Any: """simple docstring""" import torch # Classic `model_kwargs` lowerCamelCase_ = pipeline( model='hf-internal-testing/tiny-random-bloom' , model_kwargs={'device_map': 'auto', 'torch_dtype': torch.bfloataa} , ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) lowerCamelCase_ = pipe('This is a test' ) self.assertEqual( A_ , [ { 'generated_text': ( 'This is a test test test test test test test test test test test test test test test test' ' test' ) } ] , ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) lowerCamelCase_ = pipeline(model='hf-internal-testing/tiny-random-bloom' , device_map='auto' , torch_dtype=torch.bfloataa ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa ) lowerCamelCase_ = pipe('This is a test' ) self.assertEqual( A_ , [ { 'generated_text': ( 'This is a test test test test test test test test test test test test test test test test' ' test' ) } ] , ) # torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602 lowerCamelCase_ = pipeline(model='hf-internal-testing/tiny-random-bloom' , device_map='auto' ) self.assertEqual(pipe.model.device , torch.device(0 ) ) self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa ) lowerCamelCase_ = pipe('This is a test' ) self.assertEqual( A_ , [ { 'generated_text': ( 'This is a test test test test test test test test test test test test test test test test' ' test' ) } ] , ) @require_torch @require_torch_gpu def a__ ( self : int ) -> str: """simple docstring""" import torch lowerCamelCase_ = pipeline(model='hf-internal-testing/tiny-random-bloom' , device=0 , torch_dtype=torch.floataa ) pipe('This is a test' ) @require_torch @require_accelerate @require_torch_gpu def a__ ( self : List[Any] ) -> Dict: """simple docstring""" import torch lowerCamelCase_ = pipeline(model='hf-internal-testing/tiny-random-bloom' , device_map='auto' , torch_dtype=torch.floataa ) pipe('This is a test' , do_sample=A_ , top_p=0.5 ) def a__ ( self : Tuple ) -> Dict: """simple docstring""" lowerCamelCase_ = 'Hello world' lowerCamelCase_ = pipeline('text-generation' , model='hf-internal-testing/tiny-random-gpt2' ) if text_generator.model.framework == "tf": lowerCamelCase_ = logging.get_logger('transformers.generation.tf_utils' ) else: lowerCamelCase_ = logging.get_logger('transformers.generation.utils' ) lowerCamelCase_ = 'Both `max_new_tokens`' # The beggining of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(A_ ) as cl: lowerCamelCase_ = text_generator(A_ , max_length=10 , max_new_tokens=1 ) self.assertIn(A_ , cl.out ) # The user only sets one -> no warning with CaptureLogger(A_ ) as cl: lowerCamelCase_ = text_generator(A_ , max_new_tokens=1 ) self.assertNotIn(A_ , cl.out ) with CaptureLogger(A_ ) as cl: lowerCamelCase_ = text_generator(A_ , max_length=10 ) self.assertNotIn(A_ , cl.out )
651
0
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case : int = logging.get_logger(__name__) snake_case : Optional[Any] = { """kakaobrain/align-base""": """https://huggingface.co/kakaobrain/align-base/resolve/main/config.json""", } class __lowercase ( UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = "align_text_model" def __init__( self , A_=30522 , A_=768 , A_=12 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=2 , A_=0.02 , A_=1e-1_2 , A_=0 , A_="absolute" , A_=True , **A_ , )-> List[str]: super().__init__(**UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = pad_token_id @classmethod def __magic_name__ ( cls , A_ , **A_ )-> "PretrainedConfig": cls._set_token_in_kwargs(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(UpperCamelCase__ , **UpperCamelCase__ ) # get the text config dict if we are loading from AlignConfig if config_dict.get('model_type' ) == "align": _SCREAMING_SNAKE_CASE = config_dict['text_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCamelCase__ , **UpperCamelCase__ ) class __lowercase ( UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = "align_vision_model" def __init__( self , A_ = 3 , A_ = 600 , A_ = 2.0 , A_ = 3.1 , A_ = 8 , A_ = [3, 3, 5, 3, 5, 5, 3] , A_ = [32, 16, 24, 40, 80, 112, 192] , A_ = [16, 24, 40, 80, 112, 192, 320] , A_ = [] , A_ = [1, 2, 2, 2, 1, 2, 1] , A_ = [1, 2, 2, 3, 3, 4, 1] , A_ = [1, 6, 6, 6, 6, 6, 6] , A_ = 0.25 , A_ = "swish" , A_ = 2560 , A_ = "mean" , A_ = 0.02 , A_ = 0.001 , A_ = 0.99 , A_ = 0.2 , **A_ , )-> Union[str, Any]: super().__init__(**UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = width_coefficient _SCREAMING_SNAKE_CASE = depth_coefficient _SCREAMING_SNAKE_CASE = depth_divisor _SCREAMING_SNAKE_CASE = kernel_sizes _SCREAMING_SNAKE_CASE = in_channels _SCREAMING_SNAKE_CASE = out_channels _SCREAMING_SNAKE_CASE = depthwise_padding _SCREAMING_SNAKE_CASE = strides _SCREAMING_SNAKE_CASE = num_block_repeats _SCREAMING_SNAKE_CASE = expand_ratios _SCREAMING_SNAKE_CASE = squeeze_expansion_ratio _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = hidden_dim _SCREAMING_SNAKE_CASE = pooling_type _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = batch_norm_eps _SCREAMING_SNAKE_CASE = batch_norm_momentum _SCREAMING_SNAKE_CASE = drop_connect_rate _SCREAMING_SNAKE_CASE = sum(UpperCamelCase__ ) * 4 @classmethod def __magic_name__ ( cls , A_ , **A_ )-> "PretrainedConfig": cls._set_token_in_kwargs(UpperCamelCase__ ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(UpperCamelCase__ , **UpperCamelCase__ ) # get the vision config dict if we are loading from AlignConfig if config_dict.get('model_type' ) == "align": _SCREAMING_SNAKE_CASE = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(UpperCamelCase__ , **UpperCamelCase__ ) class __lowercase ( UpperCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = "align" SCREAMING_SNAKE_CASE : Union[str, Any] = True def __init__( self , A_=None , A_=None , A_=640 , A_=1.0 , A_=0.02 , **A_ , )-> Union[str, Any]: super().__init__(**UpperCamelCase__ ) if text_config is None: _SCREAMING_SNAKE_CASE = {} logger.info('text_config is None. Initializing the AlignTextConfig with default values.' ) if vision_config is None: _SCREAMING_SNAKE_CASE = {} logger.info('vision_config is None. Initializing the AlignVisionConfig with default values.' ) _SCREAMING_SNAKE_CASE = AlignTextConfig(**UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = AlignVisionConfig(**UpperCamelCase__ ) _SCREAMING_SNAKE_CASE = projection_dim _SCREAMING_SNAKE_CASE = temperature_init_value _SCREAMING_SNAKE_CASE = initializer_range @classmethod def __magic_name__ ( cls , A_ , A_ , **A_ )-> List[Any]: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **UpperCamelCase__ ) def __magic_name__ ( self )-> Optional[int]: _SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) _SCREAMING_SNAKE_CASE = self.text_config.to_dict() _SCREAMING_SNAKE_CASE = self.vision_config.to_dict() _SCREAMING_SNAKE_CASE = self.__class__.model_type return output
605
"""simple docstring""" from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer @dataclass class lowerCAmelCase ( a ): """simple docstring""" __lowercase :torch.FloatTensor class lowerCAmelCase ( a , a ): """simple docstring""" @register_to_config def __init__( self , UpperCamelCase__ = 3 , UpperCamelCase__ = 3 , UpperCamelCase__ = ("DownEncoderBlock2D",) , UpperCamelCase__ = ("UpDecoderBlock2D",) , UpperCamelCase__ = (64,) , UpperCamelCase__ = 1 , UpperCamelCase__ = "silu" , UpperCamelCase__ = 3 , UpperCamelCase__ = 32 , UpperCamelCase__ = 256 , UpperCamelCase__ = 32 , UpperCamelCase__ = None , UpperCamelCase__ = 0.18_215 , UpperCamelCase__ = "group" , ) -> Any: '''simple docstring''' super().__init__() # pass init params to Encoder lowerCamelCase_ = Encoder( in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , down_block_types=UpperCamelCase__ , block_out_channels=UpperCamelCase__ , layers_per_block=UpperCamelCase__ , act_fn=UpperCamelCase__ , norm_num_groups=UpperCamelCase__ , double_z=UpperCamelCase__ , ) lowerCamelCase_ = vq_embed_dim if vq_embed_dim is not None else latent_channels lowerCamelCase_ = nn.Convad(UpperCamelCase__ , UpperCamelCase__ , 1 ) lowerCamelCase_ = VectorQuantizer(UpperCamelCase__ , UpperCamelCase__ , beta=0.25 , remap=UpperCamelCase__ , sane_index_shape=UpperCamelCase__ ) lowerCamelCase_ = nn.Convad(UpperCamelCase__ , UpperCamelCase__ , 1 ) # pass init params to Decoder lowerCamelCase_ = Decoder( in_channels=UpperCamelCase__ , out_channels=UpperCamelCase__ , up_block_types=UpperCamelCase__ , block_out_channels=UpperCamelCase__ , layers_per_block=UpperCamelCase__ , act_fn=UpperCamelCase__ , norm_num_groups=UpperCamelCase__ , norm_type=UpperCamelCase__ , ) @apply_forward_hook def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ = True ) -> VQEncoderOutput: '''simple docstring''' lowerCamelCase_ = self.encoder(UpperCamelCase__ ) lowerCamelCase_ = self.quant_conv(UpperCamelCase__ ) if not return_dict: return (h,) return VQEncoderOutput(latents=UpperCamelCase__ ) @apply_forward_hook def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ = False , UpperCamelCase__ = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' if not force_not_quantize: lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = self.quantize(UpperCamelCase__ ) else: lowerCamelCase_ = h lowerCamelCase_ = self.post_quant_conv(UpperCamelCase__ ) lowerCamelCase_ = self.decoder(UpperCamelCase__ , quant if self.config.norm_type == '''spatial''' else None ) if not return_dict: return (dec,) return DecoderOutput(sample=UpperCamelCase__ ) def _lowerCAmelCase ( self , UpperCamelCase__ , UpperCamelCase__ = True ) -> Union[DecoderOutput, torch.FloatTensor]: '''simple docstring''' lowerCamelCase_ = sample lowerCamelCase_ = self.encode(UpperCamelCase__ ).latents lowerCamelCase_ = self.decode(UpperCamelCase__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=UpperCamelCase__ )
142
0
"""simple docstring""" import re def __UpperCAmelCase ( _snake_case : str ): return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]", str_ )] def __UpperCAmelCase ( _snake_case : str ): _lowercase = split_input(str_ ) return "".join( ["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def __UpperCAmelCase ( _snake_case : str, _snake_case : bool, _snake_case : str ): try: _lowercase = split_input(_snake_case ) if upper: _lowercase = "".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: _lowercase = "".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def __UpperCAmelCase ( _snake_case : str ): return to_simple_case(_snake_case ) def __UpperCAmelCase ( _snake_case : str ): try: _lowercase = to_simple_case(_snake_case ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def __UpperCAmelCase ( _snake_case : str, _snake_case : bool ): return to_complex_case(_snake_case, _snake_case, "_" ) def __UpperCAmelCase ( _snake_case : str, _snake_case : bool ): return to_complex_case(_snake_case, _snake_case, "-" ) if __name__ == "__main__": __import__("doctest").testmod()
227
"""simple docstring""" import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig __UpperCamelCase : List[Any] = logging.get_logger(__name__) class UpperCAmelCase_ : def __init__( self : int , _lowercase : Dict , _lowercase : List[Any] ) -> Optional[int]: _lowercase = question_encoder _lowercase = generator _lowercase = self.question_encoder def _lowerCamelCase ( self : int , _lowercase : Any ) -> str: if os.path.isfile(_lowercase ): raise ValueError(f"""Provided path ({save_directory}) should be a directory, not a file""" ) os.makedirs(_lowercase , exist_ok=_lowercase ) _lowercase = os.path.join(_lowercase , "question_encoder_tokenizer" ) _lowercase = os.path.join(_lowercase , "generator_tokenizer" ) self.question_encoder.save_pretrained(_lowercase ) self.generator.save_pretrained(_lowercase ) @classmethod def _lowerCamelCase ( cls : Union[str, Any] , _lowercase : Optional[Any] , **_lowercase : Dict ) -> List[str]: # dynamically import AutoTokenizer from ..auto.tokenization_auto import AutoTokenizer _lowercase = kwargs.pop("config" , _lowercase ) if config is None: _lowercase = RagConfig.from_pretrained(_lowercase ) _lowercase = AutoTokenizer.from_pretrained( _lowercase , config=config.question_encoder , subfolder="question_encoder_tokenizer" ) _lowercase = AutoTokenizer.from_pretrained( _lowercase , config=config.generator , subfolder="generator_tokenizer" ) return cls(question_encoder=_lowercase , generator=_lowercase ) def __call__( self : str , *_lowercase : Tuple , **_lowercase : Optional[Any] ) -> str: return self.current_tokenizer(*_lowercase , **_lowercase ) def _lowerCamelCase ( self : str , *_lowercase : Any , **_lowercase : Optional[int] ) -> List[str]: return self.generator.batch_decode(*_lowercase , **_lowercase ) def _lowerCamelCase ( self : List[Any] , *_lowercase : Dict , **_lowercase : str ) -> Optional[Any]: return self.generator.decode(*_lowercase , **_lowercase ) def _lowerCamelCase ( self : List[Any] ) -> Optional[Any]: _lowercase = self.question_encoder def _lowerCamelCase ( self : Dict ) -> int: _lowercase = self.generator def _lowerCamelCase ( self : int , _lowercase : List[str] , _lowercase : Optional[List[str]] = None , _lowercase : Optional[int] = None , _lowercase : Optional[int] = None , _lowercase : str = "longest" , _lowercase : str = None , _lowercase : bool = True , **_lowercase : List[Any] , ) -> BatchEncoding: warnings.warn( "`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the " "regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` " "context manager to prepare your targets. See the documentation of your specific tokenizer for more " "details" , _lowercase , ) if max_length is None: _lowercase = self.current_tokenizer.model_max_length _lowercase = self( _lowercase , add_special_tokens=_lowercase , return_tensors=_lowercase , max_length=_lowercase , padding=_lowercase , truncation=_lowercase , **_lowercase , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: _lowercase = self.current_tokenizer.model_max_length _lowercase = self( text_target=_lowercase , add_special_tokens=_lowercase , return_tensors=_lowercase , padding=_lowercase , max_length=_lowercase , truncation=_lowercase , **_lowercase , ) _lowercase = labels["input_ids"] return model_inputs
227
1
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast 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 __magic_name__ : List[Any] = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ (lowerCAmelCase__ , unittest.TestCase ): lowercase_ : Any = XLMRobertaTokenizer lowercase_ : Dict = XLMRobertaTokenizerFast lowercase_ : Union[str, Any] = True lowercase_ : Optional[Any] = True def A__ ( self : Union[str, Any] ): """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLMRobertaTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def A__ ( self : Union[str, Any] ): """simple docstring""" lowerCAmelCase__ = "<pad>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def A__ ( self : Dict ): """simple docstring""" lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(__UpperCAmelCase ) , 10_02 ) def A__ ( self : List[Any] ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def A__ ( self : List[str] ): """simple docstring""" lowerCAmelCase__ = XLMRobertaTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(__UpperCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) lowerCAmelCase__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def A__ ( self : Optional[Any] ): """simple docstring""" 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 lowerCAmelCase__ = (self.rust_tokenizer_class, "hf-internal-testing/tiny-xlm-roberta", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): lowerCAmelCase__ = self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) lowerCAmelCase__ = self.tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) lowerCAmelCase__ = tempfile.mkdtemp() lowerCAmelCase__ = tokenizer_r.save_pretrained(__UpperCAmelCase ) lowerCAmelCase__ = tokenizer_p.save_pretrained(__UpperCAmelCase ) # 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 ) ) lowerCAmelCase__ = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(__UpperCAmelCase , __UpperCAmelCase ) # Checks everything loads correctly in the same way lowerCAmelCase__ = tokenizer_r.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__UpperCAmelCase ) # Save tokenizer rust, legacy_format=True lowerCAmelCase__ = tempfile.mkdtemp() lowerCAmelCase__ = tokenizer_r.save_pretrained(__UpperCAmelCase , legacy_format=__UpperCAmelCase ) lowerCAmelCase__ = tokenizer_p.save_pretrained(__UpperCAmelCase ) # Checks it save with the same files self.assertSequenceEqual(__UpperCAmelCase , __UpperCAmelCase ) # Checks everything loads correctly in the same way lowerCAmelCase__ = tokenizer_r.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) shutil.rmtree(__UpperCAmelCase ) # Save tokenizer rust, legacy_format=False lowerCAmelCase__ = tempfile.mkdtemp() lowerCAmelCase__ = tokenizer_r.save_pretrained(__UpperCAmelCase , legacy_format=__UpperCAmelCase ) lowerCAmelCase__ = tokenizer_p.save_pretrained(__UpperCAmelCase ) # 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 lowerCAmelCase__ = tokenizer_r.from_pretrained(__UpperCAmelCase ) lowerCAmelCase__ = tokenizer_p.from_pretrained(__UpperCAmelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCAmelCase , __UpperCAmelCase ) ) shutil.rmtree(__UpperCAmelCase ) @cached_property def A__ ( self : int ): """simple docstring""" return XLMRobertaTokenizer.from_pretrained('''xlm-roberta-base''' ) def A__ ( self : List[str] ): """simple docstring""" with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name ) lowerCAmelCase__ = XLMRobertaTokenizer(f.name , keep_accents=__UpperCAmelCase ) lowerCAmelCase__ = pickle.dumps(__UpperCAmelCase ) pickle.loads(__UpperCAmelCase ) def A__ ( self : Any ): """simple docstring""" if not self.test_rust_tokenizer: return lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = self.get_rust_tokenizer() lowerCAmelCase__ = "I was born in 92000, and this is falsé." lowerCAmelCase__ = tokenizer.tokenize(__UpperCAmelCase ) lowerCAmelCase__ = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) lowerCAmelCase__ = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) lowerCAmelCase__ = self.get_rust_tokenizer() lowerCAmelCase__ = tokenizer.encode(__UpperCAmelCase ) lowerCAmelCase__ = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) @slow def A__ ( self : int ): """simple docstring""" lowerCAmelCase__ = "Hello World!" lowerCAmelCase__ = [0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def A__ ( self : Tuple ): """simple docstring""" lowerCAmelCase__ = ( "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" ) lowerCAmelCase__ = [ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def A__ ( self : Optional[int] ): """simple docstring""" # fmt: off lowerCAmelCase__ = {"input_ids": [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name='''xlm-roberta-base''' , revision='''d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3''' , )
615
import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class _a ( lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' lowerCamelCase_ : Dict = ReformerTokenizer lowerCamelCase_ : int = ReformerTokenizerFast lowerCamelCase_ : Optional[Any] = True lowerCamelCase_ : List[str] = False lowerCamelCase_ : Optional[int] = True def __UpperCAmelCase( self ): super().setUp() __A : List[Any] = ReformerTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCAmelCase( self ): __A : Any = "<s>" __A : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase ) , __UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase ) , __UpperCAmelCase ) def __UpperCAmelCase( self ): __A : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__UpperCAmelCase ) , 1_000 ) def __UpperCAmelCase( self ): self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def __UpperCAmelCase( self ): if not self.test_rust_tokenizer: return __A : Union[str, Any] = self.get_tokenizer() __A : Optional[int] = self.get_rust_tokenizer() __A : Union[str, Any] = "I was born in 92000, and this is falsé." __A : List[str] = tokenizer.tokenize(__UpperCAmelCase ) __A : List[Any] = rust_tokenizer.tokenize(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) __A : List[Any] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) __A : Optional[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) __A : List[Any] = self.get_rust_tokenizer() __A : Union[str, Any] = tokenizer.encode(__UpperCAmelCase ) __A : Union[str, Any] = rust_tokenizer.encode(__UpperCAmelCase ) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase ) def __UpperCAmelCase( self , __UpperCAmelCase=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): __A : Tuple = self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase ) # Simple input __A : Optional[int] = "This is a simple input" __A : Tuple = ["This is a simple input 1", "This is a simple input 2"] __A : Any = ("This is a simple input", "This is a pair") __A : Any = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(__UpperCAmelCase , tokenizer_r.encode , __UpperCAmelCase , max_length=__UpperCAmelCase , padding="max_length" ) # Simple input self.assertRaises(__UpperCAmelCase , tokenizer_r.encode_plus , __UpperCAmelCase , max_length=__UpperCAmelCase , padding="max_length" ) # Simple input self.assertRaises( __UpperCAmelCase , tokenizer_r.batch_encode_plus , __UpperCAmelCase , max_length=__UpperCAmelCase , padding="max_length" , ) # Pair input self.assertRaises(__UpperCAmelCase , tokenizer_r.encode , __UpperCAmelCase , max_length=__UpperCAmelCase , padding="max_length" ) # Pair input self.assertRaises(__UpperCAmelCase , tokenizer_r.encode_plus , __UpperCAmelCase , max_length=__UpperCAmelCase , padding="max_length" ) # Pair input self.assertRaises( __UpperCAmelCase , tokenizer_r.batch_encode_plus , __UpperCAmelCase , max_length=__UpperCAmelCase , padding="max_length" , ) def __UpperCAmelCase( self ): pass def __UpperCAmelCase( self ): __A : Tuple = ReformerTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase ) __A : List[str] = tokenizer.tokenize("This is a test" ) self.assertListEqual(__UpperCAmelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) , [285, 46, 10, 170, 382] , ) __A : Optional[Any] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) __A : Tuple = tokenizer.convert_tokens_to_ids(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __A : int = tokenizer.convert_ids_to_tokens(__UpperCAmelCase ) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def __UpperCAmelCase( self ): return ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment" ) @slow def __UpperCAmelCase( self ): __A : Any = "Hello World!" __A : Optional[int] = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @slow def __UpperCAmelCase( self ): __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" ) __A : Union[str, Any] = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase ) ) @require_torch @slow def __UpperCAmelCase( self ): import torch from transformers import ReformerConfig, ReformerModel # Build sequence __A : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10] __A : Optional[Any] = " ".join(__UpperCAmelCase ) __A : Tuple = self.big_tokenizer.encode_plus(__UpperCAmelCase , return_tensors="pt" ) __A : Dict = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="pt" ) __A : Union[str, Any] = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) __A : Dict = encoded_sequence["input_ids"].shape __A : int = ReformerModel(__UpperCAmelCase ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__UpperCAmelCase ) model(**__UpperCAmelCase ) @slow def __UpperCAmelCase( self ): # fmt: off __A : Dict = {"input_ids": [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], "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]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 __A : int = [ "This is a very simple sentence.", "The quick brown fox jumps over the lazy dog.", ] self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name="google/reformer-crime-and-punishment" , revision="0e6c3decb8211d49bf881013425dc8b0448b3f5a" , padding=__UpperCAmelCase , sequences=__UpperCAmelCase , )
520
0
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase__ ( _A , _A , _A , _A="attention" ): """simple docstring""" a_ = params[f"{prefix}/layers_{i}/{layer_name}/key/kernel"] a_ = params[f"{prefix}/layers_{i}/{layer_name}/out/kernel"] a_ = params[f"{prefix}/layers_{i}/{layer_name}/query/kernel"] a_ = params[f"{prefix}/layers_{i}/{layer_name}/value/kernel"] return k, o, q, v def UpperCAmelCase__ ( _A , _A , _A , _A=False ): """simple docstring""" if split_mlp_wi: a_ = params[f"{prefix}/layers_{i}/mlp/wi_0/kernel"] a_ = params[f"{prefix}/layers_{i}/mlp/wi_1/kernel"] a_ = (wi_a, wi_a) else: a_ = params[f"{prefix}/layers_{i}/mlp/wi/kernel"] a_ = params[f"{prefix}/layers_{i}/mlp/wo/kernel"] return wi, wo def UpperCAmelCase__ ( _A , _A , _A , _A ): """simple docstring""" return params[f"{prefix}/layers_{i}/{layer_name}/scale"] def UpperCAmelCase__ ( _A , *, _A , _A ): """simple docstring""" a_ = traverse_util.flatten_dict(variables['''target'''] ) a_ = {'''/'''.join(_A ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi a_ = '''encoder/layers_0/mlp/wi_0/kernel''' in old print('''Split MLP:''' , _A ) a_ = collections.OrderedDict() # Shared embeddings. a_ = old['''token_embedder/embedding'''] # Encoder. for i in range(_A ): # Block i, layer 0 (Self Attention). a_ = tax_layer_norm_lookup(_A , _A , '''encoder''' , '''pre_attention_layer_norm''' ) a_ , a_ , a_ , a_ = tax_attention_lookup(_A , _A , '''encoder''' , '''attention''' ) a_ = layer_norm a_ = k.T a_ = o.T a_ = q.T a_ = v.T # Block i, layer 1 (MLP). a_ = tax_layer_norm_lookup(_A , _A , '''encoder''' , '''pre_mlp_layer_norm''' ) a_ , a_ = tax_mlp_lookup(_A , _A , '''encoder''' , _A ) a_ = layer_norm if split_mlp_wi: a_ = wi[0].T a_ = wi[1].T else: a_ = wi.T a_ = wo.T a_ = old[ '''encoder/relpos_bias/rel_embedding''' ].T a_ = old['''encoder/encoder_norm/scale'''] if not is_encoder_only: # Decoder. for i in range(_A ): # Block i, layer 0 (Self Attention). a_ = tax_layer_norm_lookup(_A , _A , '''decoder''' , '''pre_self_attention_layer_norm''' ) a_ , a_ , a_ , a_ = tax_attention_lookup(_A , _A , '''decoder''' , '''self_attention''' ) a_ = layer_norm a_ = k.T a_ = o.T a_ = q.T a_ = v.T # Block i, layer 1 (Cross Attention). a_ = tax_layer_norm_lookup(_A , _A , '''decoder''' , '''pre_cross_attention_layer_norm''' ) a_ , a_ , a_ , a_ = tax_attention_lookup(_A , _A , '''decoder''' , '''encoder_decoder_attention''' ) a_ = layer_norm a_ = k.T a_ = o.T a_ = q.T a_ = v.T # Block i, layer 2 (MLP). a_ = tax_layer_norm_lookup(_A , _A , '''decoder''' , '''pre_mlp_layer_norm''' ) a_ , a_ = tax_mlp_lookup(_A , _A , '''decoder''' , _A ) a_ = layer_norm if split_mlp_wi: a_ = wi[0].T a_ = wi[1].T else: a_ = wi.T a_ = wo.T a_ = old['''decoder/decoder_norm/scale'''] a_ = old[ '''decoder/relpos_bias/rel_embedding''' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: a_ = old['''decoder/logits_dense/kernel'''].T return new def UpperCAmelCase__ ( _A , _A ): """simple docstring""" a_ = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: a_ = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: a_ = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) a_ = state_dict['''shared.weight'''] return state_dict def UpperCAmelCase__ ( _A , _A , _A , _A ): """simple docstring""" a_ = checkpoints.load_tax_checkpoint(_A ) a_ = convert_tax_to_pytorch(_A , num_layers=config.num_layers , is_encoder_only=_A ) a_ = make_state_dict(_A , _A ) model.load_state_dict(_A , strict=_A ) def UpperCAmelCase__ ( _A , _A , _A , _A = False ): """simple docstring""" a_ = TaConfig.from_json_file(_A ) print(f"Building PyTorch model from configuration: {config}" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: a_ = TaEncoderModel(_A ) else: a_ = TaForConditionalGeneration(_A ) # Load weights from tf checkpoint load_tax_weights_in_ta(_A , _A , _A , _A ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(_A ) # Verify that we can load the checkpoint. model.from_pretrained(_A ) print('''Done''' ) if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) UpperCamelCase__ = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
143
from __future__ import annotations def UpperCAmelCase__ ( _A ): """simple docstring""" a_ = [True] * limit a_ = False a_ = False a_ = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): a_ = i * 2 while index < limit: a_ = False a_ = index + i a_ = [2] for i in range(3 , _A , 2 ): if is_prime[i]: primes.append(_A ) return primes def UpperCAmelCase__ ( _A = 1_000_000 ): """simple docstring""" a_ = prime_sieve(_A ) a_ = 0 a_ = 0 for i in range(len(_A ) ): for j in range(i + length , len(_A ) ): a_ = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: a_ = j - i a_ = sol return largest if __name__ == "__main__": print(F"""{solution() = }""")
143
1
import random def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> Dict: _UpperCAmelCase = a[left_index] _UpperCAmelCase = left_index + 1 for j in range(left_index + 1 , snake_case ): if a[j] < pivot: _UpperCAmelCase , _UpperCAmelCase = a[i], a[j] i += 1 _UpperCAmelCase , _UpperCAmelCase = a[i - 1], a[left_index] return i - 1 def _SCREAMING_SNAKE_CASE ( snake_case , snake_case , snake_case ) -> List[Any]: if left < right: _UpperCAmelCase = random.randint(snake_case , right - 1 ) _UpperCAmelCase , _UpperCAmelCase = ( a[left], a[pivot], ) # switches the pivot with the left most bound _UpperCAmelCase = partition(snake_case , snake_case , snake_case ) quick_sort_random( snake_case , snake_case , snake_case ) # recursive quicksort to the left of the pivot point quick_sort_random( snake_case , pivot_index + 1 , snake_case ) # recursive quicksort to the right of the pivot point def _SCREAMING_SNAKE_CASE ( ) -> List[str]: _UpperCAmelCase = input("""Enter numbers separated by a comma:\n""" ).strip() _UpperCAmelCase = [int(snake_case ) for item in user_input.split(""",""" )] quick_sort_random(snake_case , 0 , len(snake_case ) ) print(snake_case ) if __name__ == "__main__": main()
518
def _SCREAMING_SNAKE_CASE ( snake_case = 1_0_0_0 ) -> int: _UpperCAmelCase , _UpperCAmelCase = 1, 1 _UpperCAmelCase = [] for i in range(1 , n + 1 ): _UpperCAmelCase = prev_numerator + 2 * prev_denominator _UpperCAmelCase = prev_numerator + prev_denominator if len(str(snake_case ) ) > len(str(snake_case ) ): result.append(snake_case ) _UpperCAmelCase = numerator _UpperCAmelCase = denominator return len(snake_case ) if __name__ == "__main__": print(F'{solution() = }')
518
1
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __SCREAMING_SNAKE_CASE : def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : Tuple , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : List[str] ): return None class __SCREAMING_SNAKE_CASE : def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Dict , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[str] ): return None class __SCREAMING_SNAKE_CASE ( unittest.TestCase): __SCREAMING_SNAKE_CASE : Optional[int] = [ # (model_name, model_kwargs) ("""bert-base-cased""", {}), ("""gpt2""", {"""use_cache""": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCAmelCase__ ( self : Optional[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__UpperCamelCase , "tf" , 12 , **__UpperCamelCase ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__UpperCamelCase , "pt" , 12 , **__UpperCamelCase ) @require_torch @slow def UpperCAmelCase__ ( self : Any ): from transformers import BertModel _UpperCAmelCase = ["[UNK]", "[SEP]", "[CLS]", "[PAD]", "[MASK]", "some", "other", "words"] with NamedTemporaryFile(mode="w+t" ) as vocab_file: vocab_file.write("\n".join(__UpperCamelCase ) ) vocab_file.flush() _UpperCAmelCase = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: _UpperCAmelCase = BertModel(BertConfig(vocab_size=len(__UpperCamelCase ) ) ) model.save_pretrained(__UpperCamelCase ) self._test_export(__UpperCamelCase , "pt" , 12 , __UpperCamelCase ) @require_tf @slow def UpperCAmelCase__ ( self : Optional[int] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: _UpperCAmelCase = self._test_export(__UpperCamelCase , "tf" , 12 , **__UpperCamelCase ) _UpperCAmelCase = quantize(Path(__UpperCamelCase ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__UpperCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) @require_torch @slow def UpperCAmelCase__ ( self : Union[str, Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: _UpperCAmelCase = self._test_export(__UpperCamelCase , "pt" , 12 , **__UpperCamelCase ) _UpperCAmelCase = quantize(__UpperCamelCase ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__UpperCamelCase ).stat().st_size: self.fail("Quantized model is bigger than initial ONNX model" ) def UpperCAmelCase__ ( self : int , __UpperCamelCase : Tuple , __UpperCamelCase : int , __UpperCamelCase : Dict , __UpperCamelCase : Any=None , **__UpperCamelCase : Optional[Any] ): try: # Compute path with TemporaryDirectory() as tempdir: _UpperCAmelCase = Path(__UpperCamelCase ).joinpath("model.onnx" ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , **__UpperCamelCase ) return path except Exception as e: self.fail(__UpperCamelCase ) @require_torch @require_tokenizers @slow def UpperCAmelCase__ ( self : List[Any] ): from transformers import BertModel _UpperCAmelCase = BertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) _UpperCAmelCase = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__UpperCamelCase , __UpperCamelCase , "pt" ) @require_tf @require_tokenizers @slow def UpperCAmelCase__ ( self : List[str] ): from transformers import TFBertModel _UpperCAmelCase = TFBertModel(BertConfig.from_pretrained("lysandre/tiny-bert-random" ) ) _UpperCAmelCase = BertTokenizerFast.from_pretrained("lysandre/tiny-bert-random" ) self._test_infer_dynamic_axis(__UpperCamelCase , __UpperCamelCase , "tf" ) def UpperCAmelCase__ ( self : Optional[int] , __UpperCamelCase : Optional[Any] , __UpperCamelCase : Tuple , __UpperCamelCase : int ): _UpperCAmelCase = FeatureExtractionPipeline(__UpperCamelCase , __UpperCamelCase ) _UpperCAmelCase = ["input_ids", "token_type_ids", "attention_mask", "output_0", "output_1"] _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = infer_shapes(__UpperCamelCase , __UpperCamelCase ) # Assert all variables are present self.assertEqual(len(__UpperCamelCase ) , len(__UpperCamelCase ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __UpperCamelCase ) self.assertSequenceEqual(variable_names[3:] , __UpperCamelCase ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: "batch", 1: "sequence"} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes["output_0"] , {0: "batch", 1: "sequence"} ) self.assertDictEqual(shapes["output_1"] , {0: "batch"} ) def UpperCAmelCase__ ( self : Tuple ): _UpperCAmelCase = ["input_ids", "attention_mask", "token_type_ids"] _UpperCAmelCase = {"input_ids": [1, 2, 3, 4], "attention_mask": [0, 0, 0, 0], "token_type_ids": [1, 1, 1, 1]} _UpperCAmelCase , _UpperCAmelCase = ensure_valid_input(FuncContiguousArgs() , __UpperCamelCase , __UpperCamelCase ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__UpperCamelCase ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__UpperCamelCase ) , set(__UpperCamelCase ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__UpperCamelCase , (tokens["input_ids"], tokens["token_type_ids"], tokens["attention_mask"]) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) _UpperCAmelCase , _UpperCAmelCase = ensure_valid_input(FuncNonContiguousArgs() , __UpperCamelCase , __UpperCamelCase ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__UpperCamelCase ) , 1 ) self.assertEqual(len(__UpperCamelCase ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens["input_ids"] ) self.assertEqual(ordered_input_names[0] , "input_ids" ) def UpperCAmelCase__ ( self : str ): _UpperCAmelCase = generate_identified_filename(Path("/home/something/my_fake_model.onnx" ) , "-test" ) self.assertEqual("/home/something/my_fake_model-test.onnx" , generated.as_posix() )
705
import inspect import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __SCREAMING_SNAKE_CASE : def __init__( self : Optional[int] , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[str]=13 , __UpperCamelCase : str=[30, 30] , __UpperCamelCase : Optional[int]=2 , __UpperCamelCase : int=3 , __UpperCamelCase : int=True , __UpperCamelCase : Optional[Any]=True , __UpperCamelCase : Any=32 , __UpperCamelCase : List[str]=5 , __UpperCamelCase : Optional[int]=4 , __UpperCamelCase : Tuple=37 , __UpperCamelCase : Optional[int]="gelu" , __UpperCamelCase : List[str]=0.1 , __UpperCamelCase : Dict=0.1 , __UpperCamelCase : List[str]=10 , __UpperCamelCase : Any=0.02 , __UpperCamelCase : str=3 , __UpperCamelCase : List[Any]=None , __UpperCamelCase : Optional[int]=8 , __UpperCamelCase : str=10 , ): _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = is_training _UpperCAmelCase = use_labels _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = num_labels _UpperCAmelCase = scope _UpperCAmelCase = n_targets _UpperCAmelCase = num_detection_tokens # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens _UpperCAmelCase = (image_size[1] // patch_size) * (image_size[0] // patch_size) _UpperCAmelCase = num_patches + 1 + self.num_detection_tokens def UpperCAmelCase__ ( self : int ): _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]] ) _UpperCAmelCase = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) _UpperCAmelCase = [] for i in range(self.batch_size ): _UpperCAmelCase = {} _UpperCAmelCase = torch.randint( high=self.num_labels , size=(self.n_targets,) , device=__UpperCamelCase ) _UpperCAmelCase = torch.rand(self.n_targets , 4 , device=__UpperCamelCase ) labels.append(__UpperCamelCase ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self : Tuple ): return YolosConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__UpperCamelCase , initializer_range=self.initializer_range , num_detection_tokens=self.num_detection_tokens , num_labels=self.num_labels , ) def UpperCAmelCase__ ( self : int , __UpperCamelCase : Tuple , __UpperCamelCase : Tuple , __UpperCamelCase : str ): _UpperCAmelCase = YolosModel(config=__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() _UpperCAmelCase = model(__UpperCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.expected_seq_len, self.hidden_size) ) def UpperCAmelCase__ ( self : Tuple , __UpperCamelCase : Optional[Any] , __UpperCamelCase : int , __UpperCamelCase : int ): _UpperCAmelCase = YolosForObjectDetection(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() _UpperCAmelCase = model(pixel_values=__UpperCamelCase ) _UpperCAmelCase = model(__UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) _UpperCAmelCase = model(pixel_values=__UpperCamelCase , labels=__UpperCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_detection_tokens, self.num_labels + 1) ) self.parent.assertEqual(result.pred_boxes.shape , (self.batch_size, self.num_detection_tokens, 4) ) def UpperCAmelCase__ ( self : List[str] ): _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( lowercase , lowercase , unittest.TestCase): __SCREAMING_SNAKE_CASE : int = (YolosModel, YolosForObjectDetection) if is_torch_available() else () __SCREAMING_SNAKE_CASE : List[str] = ( {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {} ) __SCREAMING_SNAKE_CASE : Any = False __SCREAMING_SNAKE_CASE : str = False __SCREAMING_SNAKE_CASE : Dict = False __SCREAMING_SNAKE_CASE : Dict = False def UpperCAmelCase__ ( self : Dict , __UpperCamelCase : Union[str, Any] , __UpperCamelCase : int , __UpperCamelCase : str=False ): _UpperCAmelCase = super()._prepare_for_class(__UpperCamelCase , __UpperCamelCase , return_labels=__UpperCamelCase ) if return_labels: if model_class.__name__ == "YolosForObjectDetection": _UpperCAmelCase = [] for i in range(self.model_tester.batch_size ): _UpperCAmelCase = {} _UpperCAmelCase = torch.ones( size=(self.model_tester.n_targets,) , device=__UpperCamelCase , dtype=torch.long ) _UpperCAmelCase = torch.ones( self.model_tester.n_targets , 4 , device=__UpperCamelCase , dtype=torch.float ) labels.append(__UpperCamelCase ) _UpperCAmelCase = labels return inputs_dict def UpperCAmelCase__ ( self : Optional[Any] ): _UpperCAmelCase = YolosModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=__UpperCamelCase , has_text_modality=__UpperCamelCase , hidden_size=37 ) def UpperCAmelCase__ ( self : Dict ): self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : List[Any] ): # YOLOS does not use inputs_embeds pass def UpperCAmelCase__ ( self : List[Any] ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(__UpperCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__UpperCamelCase , nn.Linear ) ) def UpperCAmelCase__ ( self : Optional[int] ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(__UpperCamelCase ) _UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ["pixel_values"] self.assertListEqual(arg_names[:1] , __UpperCamelCase ) def UpperCAmelCase__ ( self : Dict ): _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCamelCase ) def UpperCAmelCase__ ( self : Dict ): _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = True # in YOLOS, the seq_len is different _UpperCAmelCase = self.model_tester.expected_seq_len for model_class in self.all_model_classes: _UpperCAmelCase = True _UpperCAmelCase = False _UpperCAmelCase = True _UpperCAmelCase = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) _UpperCAmelCase = outputs.attentions self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _UpperCAmelCase = True _UpperCAmelCase = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) _UpperCAmelCase = outputs.attentions self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) _UpperCAmelCase = len(__UpperCamelCase ) # Check attention is always last and order is fine _UpperCAmelCase = True _UpperCAmelCase = True _UpperCAmelCase = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) _UpperCAmelCase = 1 self.assertEqual(out_len + added_hidden_states , len(__UpperCamelCase ) ) _UpperCAmelCase = outputs.attentions self.assertEqual(len(__UpperCamelCase ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def UpperCAmelCase__ ( self : Tuple ): def check_hidden_states_output(__UpperCamelCase : Dict , __UpperCamelCase : int , __UpperCamelCase : List[str] ): _UpperCAmelCase = model_class(__UpperCamelCase ) model.to(__UpperCamelCase ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(__UpperCamelCase , __UpperCamelCase ) ) _UpperCAmelCase = outputs.hidden_states _UpperCAmelCase = getattr( self.model_tester , "expected_num_hidden_layers" , self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) # YOLOS has a different seq_length _UpperCAmelCase = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = True check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True check_hidden_states_output(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) def UpperCAmelCase__ ( self : Dict ): _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*__UpperCamelCase ) @slow def UpperCAmelCase__ ( self : Optional[int] ): for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = YolosModel.from_pretrained(__UpperCamelCase ) self.assertIsNotNone(__UpperCamelCase ) def __lowerCamelCase ( ) -> Any: _UpperCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase): @cached_property def UpperCAmelCase__ ( self : Union[str, Any] ): return AutoImageProcessor.from_pretrained("hustvl/yolos-small" ) if is_vision_available() else None @slow def UpperCAmelCase__ ( self : List[str] ): _UpperCAmelCase = YolosForObjectDetection.from_pretrained("hustvl/yolos-small" ).to(__UpperCamelCase ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=__UpperCamelCase , return_tensors="pt" ).to(__UpperCamelCase ) # forward pass with torch.no_grad(): _UpperCAmelCase = model(inputs.pixel_values ) # verify outputs _UpperCAmelCase = torch.Size((1, 100, 92) ) self.assertEqual(outputs.logits.shape , __UpperCamelCase ) _UpperCAmelCase = torch.tensor( [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]] , device=__UpperCamelCase , ) _UpperCAmelCase = torch.tensor( [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]] , device=__UpperCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , __UpperCamelCase , atol=1e-4 ) ) self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3] , __UpperCamelCase , atol=1e-4 ) ) # verify postprocessing _UpperCAmelCase = image_processor.post_process_object_detection( __UpperCamelCase , threshold=0.3 , target_sizes=[image.size[::-1]] )[0] _UpperCAmelCase = torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861] ).to(__UpperCamelCase ) _UpperCAmelCase = [75, 75, 17, 63, 17] _UpperCAmelCase = torch.tensor([335.0609, 79.3848, 375.4216, 187.2495] ).to(__UpperCamelCase ) self.assertEqual(len(results["scores"] ) , 5 ) self.assertTrue(torch.allclose(results["scores"] , __UpperCamelCase , atol=1e-4 ) ) self.assertSequenceEqual(results["labels"].tolist() , __UpperCamelCase ) self.assertTrue(torch.allclose(results["boxes"][0, :] , __UpperCamelCase ) )
129
0
'''simple docstring''' import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging __lowerCAmelCase : Dict = logging.get_logger(__name__) def lowerCAmelCase ( UpperCamelCase__ : Tuple , UpperCamelCase__ : Any ): """simple docstring""" __UpperCAmelCase = set() __UpperCAmelCase = [] def parse_line(UpperCamelCase__ : Tuple ): for line in fp: if isinstance(UpperCamelCase__ , UpperCamelCase__ ): __UpperCAmelCase = line.decode('''UTF-8''' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(''' ''' ): # process a single warning and move it to `selected_warnings`. if len(UpperCamelCase__ ) > 0: __UpperCAmelCase = '''\n'''.join(UpperCamelCase__ ) # Only keep the warnings specified in `targets` if any(f""": {x}: """ in warning for x in targets ): selected_warnings.add(UpperCamelCase__ ) buffer.clear() continue else: __UpperCAmelCase = line.strip() buffer.append(UpperCamelCase__ ) if from_gh: for filename in os.listdir(UpperCamelCase__ ): __UpperCAmelCase = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) if not os.path.isdir(UpperCamelCase__ ): # read the file if filename != "warnings.txt": continue with open(UpperCamelCase__ ) as fp: parse_line(UpperCamelCase__ ) else: try: with zipfile.ZipFile(UpperCamelCase__ ) as z: for filename in z.namelist(): if not os.path.isdir(UpperCamelCase__ ): # read the file if filename != "warnings.txt": continue with z.open(UpperCamelCase__ ) as fp: parse_line(UpperCamelCase__ ) except Exception: logger.warning( f"""{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.""" ) return selected_warnings def lowerCAmelCase ( UpperCamelCase__ : str , UpperCamelCase__ : Tuple ): """simple docstring""" __UpperCAmelCase = set() __UpperCAmelCase = [os.path.join(UpperCamelCase__ , UpperCamelCase__ ) for p in os.listdir(UpperCamelCase__ ) if (p.endswith('''.zip''' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(UpperCamelCase__ , UpperCamelCase__ ) ) return selected_warnings if __name__ == "__main__": def lowerCAmelCase ( UpperCamelCase__ : int ): """simple docstring""" return values.split(''',''' ) __lowerCAmelCase : Optional[int] = 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.") # optional parameters parser.add_argument( "--targets", default="DeprecationWarning,UserWarning,FutureWarning", type=list_str, help="Comma-separated list of target warning(s) which we want to extract.", ) parser.add_argument( "--from_gh", action="store_true", help="If running from a GitHub action workflow and collecting warnings from its artifacts.", ) __lowerCAmelCase : Tuple = parser.parse_args() __lowerCAmelCase : str = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links __lowerCAmelCase : str = 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) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("=" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts __lowerCAmelCase : str = extract_warnings(args.output_dir, args.targets) __lowerCAmelCase : Optional[Any] = sorted(selected_warnings) with open(os.path.join(args.output_dir, "selected_warnings.json"), "w", encoding="UTF-8") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
262
'''simple docstring''' import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class A : def __init__( self : List[str] , __a : Any , __a : int=9_9 , __a : Any=1_3 , __a : Tuple=7 , __a : Tuple=9 , __a : Tuple=True , __a : Union[str, Any]=True , __a : List[Any]=False , __a : Optional[Any]=3_2 , __a : str=5 , __a : Optional[int]=4 , __a : Union[str, Any]=3_7 , __a : List[str]=8 , __a : Optional[int]=0.1 , __a : List[str]=0.0_0_2 , __a : List[Any]=1 , __a : str=0 , __a : Dict=0 , __a : int=None , __a : List[Any]=None , ) -> Tuple: __UpperCAmelCase = parent __UpperCAmelCase = batch_size __UpperCAmelCase = encoder_seq_length __UpperCAmelCase = decoder_seq_length # For common tests __UpperCAmelCase = self.decoder_seq_length __UpperCAmelCase = is_training __UpperCAmelCase = use_attention_mask __UpperCAmelCase = use_labels __UpperCAmelCase = vocab_size __UpperCAmelCase = hidden_size __UpperCAmelCase = num_hidden_layers __UpperCAmelCase = num_attention_heads __UpperCAmelCase = d_ff __UpperCAmelCase = relative_attention_num_buckets __UpperCAmelCase = dropout_rate __UpperCAmelCase = initializer_factor __UpperCAmelCase = eos_token_id __UpperCAmelCase = pad_token_id __UpperCAmelCase = decoder_start_token_id __UpperCAmelCase = None __UpperCAmelCase = decoder_layers def snake_case__ ( self : Union[str, Any] ) -> int: return TaConfig.from_pretrained('''google/umt5-base''' ) def snake_case__ ( self : List[Any] , __a : List[str] , __a : str , __a : Optional[int] , __a : List[Any]=None , __a : List[Any]=None , __a : Any=None , __a : str=None , __a : Any=None , ) -> List[Any]: if attention_mask is None: __UpperCAmelCase = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __UpperCAmelCase = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __UpperCAmelCase = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=__a ) if decoder_head_mask is None: __UpperCAmelCase = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=__a ) if cross_attn_head_mask is None: __UpperCAmelCase = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=__a ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } def snake_case__ ( self : List[str] ) -> Dict: __UpperCAmelCase = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __UpperCAmelCase = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __UpperCAmelCase = input_ids.clamp(self.pad_token_id + 1 ) __UpperCAmelCase = decoder_input_ids.clamp(self.pad_token_id + 1 ) __UpperCAmelCase = self.get_config() __UpperCAmelCase = config.num_attention_heads __UpperCAmelCase = self.prepare_inputs_dict(__a , __a , __a ) return config, input_dict def snake_case__ ( self : Union[str, Any] ) -> Optional[Any]: __UpperCAmelCase , __UpperCAmelCase = self.prepare_config_and_inputs() return config, inputs_dict def snake_case__ ( self : int ) -> Optional[int]: return TaConfig( vocab_size=1_6_6 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def snake_case__ ( self : Optional[int] ) -> Any: return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def snake_case__ ( self : int , __a : Any , __a : Union[str, Any] , __a : List[Any] , __a : Dict , __a : Optional[Any] , __a : int , ) -> List[Any]: __UpperCAmelCase = UMTaModel(config=__a ) model.to(__a ) model.eval() __UpperCAmelCase = model( input_ids=__a , decoder_input_ids=__a , attention_mask=__a , decoder_attention_mask=__a , ) __UpperCAmelCase = model(input_ids=__a , decoder_input_ids=__a ) __UpperCAmelCase = result.last_hidden_state __UpperCAmelCase = result.past_key_values __UpperCAmelCase = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(__a ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def snake_case__ ( self : List[str] , __a : Any , __a : Tuple , __a : List[str] , __a : Optional[Any] , __a : Dict , __a : Any , ) -> Optional[Any]: __UpperCAmelCase = UMTaModel(config=__a ).get_decoder().to(__a ).eval() # first forward pass __UpperCAmelCase = model(__a , use_cache=__a ) __UpperCAmelCase = model(__a ) __UpperCAmelCase = model(__a , use_cache=__a ) self.parent.assertTrue(len(__a ) == len(__a ) ) self.parent.assertTrue(len(__a ) == len(__a ) + 1 ) __UpperCAmelCase , __UpperCAmelCase = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __UpperCAmelCase = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __UpperCAmelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __UpperCAmelCase = model(__a )['''last_hidden_state'''] __UpperCAmelCase = model(__a , past_key_values=__a )['''last_hidden_state'''] # select random slice __UpperCAmelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item() __UpperCAmelCase = output_from_no_past[:, -1, random_slice_idx].detach() __UpperCAmelCase = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__a , __a , atol=1e-3 ) ) def snake_case__ ( self : List[Any] , __a : Union[str, Any] , __a : Dict , ) -> Optional[int]: __UpperCAmelCase = UMTaModel(config=__a ).to(__a ).half().eval() __UpperCAmelCase = model(**__a )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(__a ).any().item() ) @require_torch class A ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): a_ = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) a_ = (UMTaForConditionalGeneration,) if is_torch_available() else () a_ = ( { '''conversational''': UMTaForConditionalGeneration, '''feature-extraction''': UMTaModel, '''summarization''': UMTaForConditionalGeneration, '''text2text-generation''': UMTaForConditionalGeneration, '''translation''': UMTaForConditionalGeneration, '''question-answering''': UMTaForQuestionAnswering, } if is_torch_available() else {} ) a_ = True a_ = False a_ = False a_ = True a_ = True # The small UMT5 model needs higher percentages for CPU/MP tests a_ = [0.8, 0.9] def snake_case__ ( self : Tuple ) -> Optional[int]: __UpperCAmelCase = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def snake_case__ ( self : str ) -> Optional[int]: __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() __UpperCAmelCase = UMTaModel(config_and_inputs[0] ).to(__a ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( __a , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , f"""{tmpdirname}/t5_test.onnx""" , export_params=__a , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def snake_case__ ( self : Union[str, Any] ) -> List[str]: __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*__a ) def snake_case__ ( self : List[Any] ) -> str: __UpperCAmelCase = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() __UpperCAmelCase = config_and_inputs[0] __UpperCAmelCase = UMTaForConditionalGeneration(__a ).eval() model.to(__a ) __UpperCAmelCase = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=__a ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=__a ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=__a ), } for attn_name, (name, mask) in zip(__a , head_masking.items() ): __UpperCAmelCase = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __UpperCAmelCase = torch.ones( config.num_decoder_layers , config.num_heads , device=__a ) __UpperCAmelCase = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=__a , return_dict_in_generate=__a , **__a , ) # We check the state of decoder_attentions and cross_attentions just from the last step __UpperCAmelCase = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip('''Does not work on the tiny model as we keep hitting edge cases.''' ) def snake_case__ ( self : Optional[int] ) -> int: pass @require_torch @require_sentencepiece @require_tokenizers class A ( unittest.TestCase ): @slow @unittest.skip( '''Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged''' ) def snake_case__ ( self : Any ) -> int: __UpperCAmelCase = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=__a ).to(__a ) __UpperCAmelCase = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=__a , legacy=__a ) __UpperCAmelCase = [ '''Bonjour monsieur <extra_id_0> bien <extra_id_1>.''', '''No se como puedo <extra_id_0>.''', '''This is the reason why we <extra_id_0> them.''', '''The <extra_id_0> walks in <extra_id_1>, seats''', '''A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''', ] __UpperCAmelCase = tokenizer(__a , return_tensors='''pt''' , padding=__a ).input_ids # fmt: off __UpperCAmelCase = torch.tensor( [ [ 3_8_5_3_0, 2_1_0_7_0_3, 2_5_6_2_9_9, 1_4_1_0, 2_5_6_2_9_8, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_2_6, 3_2_1, 6_7_1, 2_5_9_2_2, 2_5_6_2_9_9, 2_7_4, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1_4_6_0, 3_3_9, 3_1_2, 1_9_0_1_4, 1_0_6_2_0, 7_5_8, 2_5_6_2_9_9, 2_3_5_5,2_7_4, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_1_7, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 3_0_1, 2_5_6_2_9_8, 2_7_5, 1_1_9_9_8_3,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_2_0, 2_5_6_2_9_9, 1_4_8_6_9, 2_8_1, 2_2_3_4, 2_8_9, 2_2_7_5, 3_3_3,6_1_3_9_1, 2_8_9, 2_5_6_2_9_8, 5_4_3, 2_5_6_2_9_7, 1_6_8_7_1_4, 3_2_9, 2_5_6_2_9_6,2_7_4, 1], ] ) # fmt: on torch.testing.assert_allclose(__a , __a ) __UpperCAmelCase = model.generate(input_ids.to(__a ) ) __UpperCAmelCase = [ '''<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>''', '''<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', '''<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>''', ] __UpperCAmelCase = tokenizer.batch_decode(__a ) self.assertEqual(__a , __a )
262
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase_ = {'''configuration_xlnet''': ['''XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLNetConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''XLNetTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = ['''XLNetTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLNetForMultipleChoice''', '''XLNetForQuestionAnswering''', '''XLNetForQuestionAnsweringSimple''', '''XLNetForSequenceClassification''', '''XLNetForTokenClassification''', '''XLNetLMHeadModel''', '''XLNetModel''', '''XLNetPreTrainedModel''', '''load_tf_weights_in_xlnet''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ = [ '''TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLNetForMultipleChoice''', '''TFXLNetForQuestionAnsweringSimple''', '''TFXLNetForSequenceClassification''', '''TFXLNetForTokenClassification''', '''TFXLNetLMHeadModel''', '''TFXLNetMainLayer''', '''TFXLNetModel''', '''TFXLNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys lowerCamelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
719
from __future__ import annotations from typing import TypedDict class __A( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE__ = 42 SCREAMING_SNAKE_CASE__ = 42 def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) return [s[i:] + s[:i] for i in range(len(__a ) )] def __magic_name__ ( __a : str ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter s type must be str.""" ) if not s: raise ValueError("""The parameter s must not be empty.""" ) UpperCamelCase__ = all_rotations(__a ) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation UpperCamelCase__ = { "bwt_string": "".join([word[-1] for word in rotations] ), "idx_original_string": rotations.index(__a ), } return response def __magic_name__ ( __a : str , __a : int ): '''simple docstring''' if not isinstance(__a , __a ): raise TypeError("""The parameter bwt_string type must be str.""" ) if not bwt_string: raise ValueError("""The parameter bwt_string must not be empty.""" ) try: UpperCamelCase__ = int(__a ) except ValueError: raise TypeError( """The parameter idx_original_string type must be int or passive""" """ of cast to int.""" ) if idx_original_string < 0: raise ValueError("""The parameter idx_original_string must not be lower than 0.""" ) if idx_original_string >= len(__a ): raise ValueError( """The parameter idx_original_string must be lower than""" """ len(bwt_string).""" ) UpperCamelCase__ = [""""""] * len(__a ) for _ in range(len(__a ) ): for i in range(len(__a ) ): UpperCamelCase__ = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": lowerCamelCase_ = '''Provide a string that I will generate its BWT transform: ''' lowerCamelCase_ = input(entry_msg).strip() lowerCamelCase_ = bwt_transform(s) print( f'Burrows Wheeler transform for string \'{s}\' results ' f'in \'{result["bwt_string"]}\'' ) lowerCamelCase_ = reverse_bwt(result['''bwt_string'''], result['''idx_original_string''']) print( f'Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' ' f'we get original string \'{original_string}\'' )
86
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class _lowerCAmelCase( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" a : Union[str, Any] =StableDiffusionInstructPixaPixPipeline a : List[str] =TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''cross_attention_kwargs'''} a : Any =TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS a : List[str] =IMAGE_TO_IMAGE_IMAGE_PARAMS a : Union[str, Any] =IMAGE_TO_IMAGE_IMAGE_PARAMS def _a ( self ): torch.manual_seed(0 ) UpperCamelCase_: Tuple = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=3_2 , ) UpperCamelCase_: List[Any] = PNDMScheduler(skip_prk_steps=_lowerCamelCase ) torch.manual_seed(0 ) UpperCamelCase_: Optional[int] = 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 ) UpperCamelCase_: Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) UpperCamelCase_: int = CLIPTextModel(_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) UpperCamelCase_: Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def _a ( self , _lowerCamelCase , _lowerCamelCase=0 ): UpperCamelCase_: str = floats_tensor((1, 3, 3_2, 3_2) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) UpperCamelCase_: Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCamelCase_: str = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('RGB' ) if str(_lowerCamelCase ).startswith('mps' ): UpperCamelCase_: List[Any] = torch.manual_seed(_lowerCamelCase ) else: UpperCamelCase_: Tuple = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) UpperCamelCase_: Optional[Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def _a ( self ): UpperCamelCase_: List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCamelCase_: str = self.get_dummy_components() UpperCamelCase_: Dict = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) UpperCamelCase_: int = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) UpperCamelCase_: int = self.get_dummy_inputs(_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = sd_pipe(**_lowerCamelCase ).images UpperCamelCase_: Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) UpperCamelCase_: Optional[int] = np.array([0.7_5_2_6, 0.3_7_5_0, 0.4_5_4_7, 0.6_1_1_7, 0.5_8_6_6, 0.5_0_1_6, 0.4_3_2_7, 0.5_6_4_2, 0.4_8_1_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _a ( self ): UpperCamelCase_: str = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCamelCase_: int = self.get_dummy_components() UpperCamelCase_: Dict = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) UpperCamelCase_: List[Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) UpperCamelCase_: Any = self.get_dummy_inputs(_lowerCamelCase ) UpperCamelCase_: Dict = 'french fries' UpperCamelCase_: Optional[int] = sd_pipe(**_lowerCamelCase , negative_prompt=_lowerCamelCase ) UpperCamelCase_: List[str] = output.images UpperCamelCase_: List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) UpperCamelCase_: Dict = np.array([0.7_5_1_1, 0.3_6_4_2, 0.4_5_5_3, 0.6_2_3_6, 0.5_7_9_7, 0.5_0_1_3, 0.4_3_4_3, 0.5_6_1_1, 0.4_8_3_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _a ( self ): UpperCamelCase_: int = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCamelCase_: Tuple = self.get_dummy_components() UpperCamelCase_: Any = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) UpperCamelCase_: List[Any] = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) UpperCamelCase_: Dict = self.get_dummy_inputs(_lowerCamelCase ) UpperCamelCase_: List[Any] = [inputs['prompt']] * 2 UpperCamelCase_: Optional[Any] = np.array(inputs['image'] ).astype(np.floataa ) / 2_5_5.0 UpperCamelCase_: Any = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 ).to(_lowerCamelCase ) UpperCamelCase_: Tuple = image / 2 + 0.5 UpperCamelCase_: int = image.permute(0 , 3 , 1 , 2 ) UpperCamelCase_: int = image.repeat(2 , 1 , 1 , 1 ) UpperCamelCase_: List[Any] = sd_pipe(**_lowerCamelCase ).images UpperCamelCase_: List[str] = image[-1, -3:, -3:, -1] assert image.shape == (2, 3_2, 3_2, 3) UpperCamelCase_: Optional[int] = np.array([0.5_8_1_2, 0.5_7_4_8, 0.5_2_2_2, 0.5_9_0_8, 0.5_6_9_5, 0.7_1_7_4, 0.6_8_0_4, 0.5_5_2_3, 0.5_5_7_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _a ( self ): UpperCamelCase_: int = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCamelCase_: Any = self.get_dummy_components() UpperCamelCase_: str = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='scaled_linear' ) UpperCamelCase_: Dict = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) UpperCamelCase_: str = sd_pipe.to(_lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=_lowerCamelCase ) UpperCamelCase_: Union[str, Any] = self.get_dummy_inputs(_lowerCamelCase ) UpperCamelCase_: Optional[int] = sd_pipe(**_lowerCamelCase ).images UpperCamelCase_: Optional[Any] = image[0, -3:, -3:, -1] UpperCamelCase_: Tuple = [round(_lowerCamelCase , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(_lowerCamelCase ) for x in slice] ) ) assert image.shape == (1, 3_2, 3_2, 3) UpperCamelCase_: Tuple = np.array([0.7_4_1_7, 0.3_8_4_2, 0.4_7_3_2, 0.5_7_7_6, 0.5_8_9_1, 0.5_1_3_9, 0.4_0_5_2, 0.5_6_7_3, 0.4_9_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _a ( self ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def _a ( self ): UpperCamelCase_: int = self.get_dummy_components() UpperCamelCase_: Optional[Any] = StableDiffusionInstructPixaPixPipeline(**_lowerCamelCase ) UpperCamelCase_: str = VaeImageProcessor(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase ) UpperCamelCase_: Optional[Any] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) UpperCamelCase_: Dict = pipe(**self.get_dummy_inputs_by_type(_lowerCamelCase , input_image_type='pt' ) )[0] UpperCamelCase_: Union[str, Any] = components['vae'] UpperCamelCase_: Union[str, Any] = self.get_dummy_inputs_by_type(_lowerCamelCase , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): UpperCamelCase_: str = vae.encode(inputs[image_param] ).latent_dist.mode() UpperCamelCase_: Dict = pipe(**_lowerCamelCase )[0] UpperCamelCase_: str = np.abs(out - out_latents_inputs ).max() self.assertLess(_lowerCamelCase , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class _lowerCAmelCase( unittest.TestCase ): """simple docstring""" def _a ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _a ( self , _lowerCamelCase=0 ): UpperCamelCase_: int = torch.manual_seed(_lowerCamelCase ) UpperCamelCase_: int = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) UpperCamelCase_: Union[str, Any] = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def _a ( self ): UpperCamelCase_: Dict = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() UpperCamelCase_: List[str] = self.get_inputs() UpperCamelCase_: Optional[int] = pipe(**_lowerCamelCase ).images UpperCamelCase_: Dict = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) UpperCamelCase_: Optional[Any] = np.array([0.5_9_0_2, 0.6_0_1_5, 0.6_0_2_7, 0.5_9_8_3, 0.6_0_9_2, 0.6_0_6_1, 0.5_7_6_5, 0.5_7_8_5, 0.5_5_5_5] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _a ( self ): UpperCamelCase_: List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=_lowerCamelCase ) UpperCamelCase_: List[str] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() UpperCamelCase_: Union[str, Any] = self.get_inputs() UpperCamelCase_: Optional[Any] = pipe(**_lowerCamelCase ).images UpperCamelCase_: Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) UpperCamelCase_: Any = np.array([0.6_5_7_8, 0.6_8_1_7, 0.6_9_7_2, 0.6_7_6_1, 0.6_8_5_6, 0.6_9_1_6, 0.6_4_2_8, 0.6_5_1_6, 0.6_3_0_1] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _a ( self ): UpperCamelCase_: Optional[int] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=_lowerCamelCase ) UpperCamelCase_: Any = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() UpperCamelCase_: int = self.get_inputs() UpperCamelCase_: Any = pipe(**_lowerCamelCase ).images UpperCamelCase_: str = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 5_1_2, 3) UpperCamelCase_: str = np.array([0.3_8_2_8, 0.3_8_3_4, 0.3_8_1_8, 0.3_7_9_2, 0.3_8_6_5, 0.3_7_5_2, 0.3_7_9_2, 0.3_8_4_7, 0.3_7_5_3] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def _a ( self ): UpperCamelCase_: Optional[Any] = 0 def callback_fn(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) -> None: UpperCamelCase_: List[Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: UpperCamelCase_: List[str] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 6_4) UpperCamelCase_: Optional[Any] = latents[0, -3:, -3:, -1] UpperCamelCase_: Tuple = np.array([-0.2_4_6_3, -0.4_6_4_4, -0.9_7_5_6, 1.5_1_7_6, 1.4_4_1_4, 0.7_8_6_6, 0.9_8_9_7, 0.8_5_2_1, 0.7_9_8_3] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: UpperCamelCase_: str = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 6_4) UpperCamelCase_: Optional[int] = latents[0, -3:, -3:, -1] UpperCamelCase_: Any = np.array([-0.2_6_4_4, -0.4_6_2_6, -0.9_6_5_3, 1.5_1_7_6, 1.4_5_5_1, 0.7_6_8_6, 0.9_8_0_5, 0.8_4_5_2, 0.8_1_1_5] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 UpperCamelCase_: Tuple = False UpperCamelCase_: Optional[int] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=_lowerCamelCase , torch_dtype=torch.floataa ) UpperCamelCase_: Tuple = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() UpperCamelCase_: Optional[Any] = self.get_inputs() pipe(**_lowerCamelCase , callback=_lowerCamelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def _a ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() UpperCamelCase_: List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=_lowerCamelCase , torch_dtype=torch.floataa ) UpperCamelCase_: Optional[int] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() UpperCamelCase_: Union[str, Any] = self.get_inputs() UpperCamelCase_: Optional[Any] = pipe(**_lowerCamelCase ) UpperCamelCase_: str = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 1_0**9 def _a ( self ): UpperCamelCase_: Tuple = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 UpperCamelCase_: Dict = inputs['image'].resize((5_0_4, 5_0_4) ) UpperCamelCase_: int = 'timbrooks/instruct-pix2pix' UpperCamelCase_: Optional[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( _lowerCamelCase , safety_checker=_lowerCamelCase , ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) pipe.enable_attention_slicing() UpperCamelCase_: Tuple = pipe(**_lowerCamelCase ) UpperCamelCase_: Optional[int] = output.images[0] UpperCamelCase_: List[Any] = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1] assert image.shape == (5_0_4, 5_0_4, 3) UpperCamelCase_: Union[str, Any] = np.array([0.2_7_2_6, 0.2_5_2_9, 0.2_6_6_4, 0.2_6_5_5, 0.2_6_4_1, 0.2_6_4_2, 0.2_5_9_1, 0.2_6_4_9, 0.2_5_9_0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
57
'''simple docstring''' import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class a : '''simple docstring''' def __init__( self , lowerCamelCase_ , lowerCamelCase_=1_3 , lowerCamelCase_=7 , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=9_9 , lowerCamelCase_=3_2 , lowerCamelCase_=5 , lowerCamelCase_=4 , lowerCamelCase_=3_7 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=5_1_2 , lowerCamelCase_=1_6 , lowerCamelCase_=2 , lowerCamelCase_=0.02 , lowerCamelCase_=3 , lowerCamelCase_=4 , lowerCamelCase_=None , ) -> str: _a : int = parent _a : str = batch_size _a : Any = seq_length _a : Tuple = is_training _a : int = use_input_mask _a : Any = use_token_type_ids _a : List[Any] = use_labels _a : Optional[int] = vocab_size _a : str = hidden_size _a : Any = num_hidden_layers _a : List[Any] = num_attention_heads _a : Tuple = intermediate_size _a : Optional[int] = hidden_act _a : str = hidden_dropout_prob _a : Tuple = attention_probs_dropout_prob _a : List[Any] = max_position_embeddings _a : Union[str, Any] = type_vocab_size _a : Dict = type_sequence_label_size _a : List[Any] = initializer_range _a : Optional[Any] = num_labels _a : Dict = num_choices _a : Dict = scope def __UpperCamelCase ( self ) -> Dict: _a : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a : str = None if self.use_input_mask: _a : str = random_attention_mask([self.batch_size, self.seq_length] ) _a : int = None if self.use_token_type_ids: _a : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a : Union[str, Any] = None _a : Any = None _a : Optional[Any] = None if self.use_labels: _a : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) _a : List[str] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase ( self ) -> List[Any]: return LlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCamelCase_ , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> int: _a : List[Any] = LlamaModel(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() _a : Any = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ ) _a : List[Any] = model(lowerCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ) -> Any: _a : Dict = True _a : Tuple = LlamaModel(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() _a : List[Any] = model( lowerCamelCase_ , attention_mask=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , encoder_attention_mask=lowerCamelCase_ , ) _a : Optional[Any] = model( lowerCamelCase_ , attention_mask=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , ) _a : str = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ) -> Dict: _a : Dict = LlamaForCausalLM(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() _a : int = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , ) -> str: _a : Optional[Any] = True _a : Tuple = True _a : Optional[int] = LlamaForCausalLM(config=lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() # first forward pass _a : str = model( lowerCamelCase_ , attention_mask=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , encoder_attention_mask=lowerCamelCase_ , use_cache=lowerCamelCase_ , ) _a : Union[str, Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _a : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) _a : str = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _a : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) _a : List[Any] = torch.cat([input_mask, next_mask] , dim=-1 ) _a : Any = model( lowerCamelCase_ , attention_mask=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , encoder_attention_mask=lowerCamelCase_ , output_hidden_states=lowerCamelCase_ , )['hidden_states'][0] _a : List[Any] = model( lowerCamelCase_ , attention_mask=lowerCamelCase_ , encoder_hidden_states=lowerCamelCase_ , encoder_attention_mask=lowerCamelCase_ , past_key_values=lowerCamelCase_ , output_hidden_states=lowerCamelCase_ , )['hidden_states'][0] # select random slice _a : List[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() _a : int = output_from_no_past[:, -3:, random_slice_idx].detach() _a : Optional[Any] = 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(lowerCamelCase_ , lowerCamelCase_ , atol=1e-3 ) ) def __UpperCamelCase ( self ) -> Tuple: _a : Optional[int] = self.prepare_config_and_inputs() ( ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ( _a ) , ) : Dict = config_and_inputs _a : Tuple = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a ( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase : Optional[int] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () __lowerCAmelCase : int = (LlamaForCausalLM,) if is_torch_available() else () __lowerCAmelCase : int = ( { """feature-extraction""": LlamaModel, """text-classification""": LlamaForSequenceClassification, """text-generation""": LlamaForCausalLM, """zero-shot""": LlamaForSequenceClassification, } if is_torch_available() else {} ) __lowerCAmelCase : str = False __lowerCAmelCase : List[Any] = False def __UpperCamelCase ( self ) -> str: _a : Optional[int] = LlamaModelTester(self ) _a : Tuple = ConfigTester(self , config_class=lowerCamelCase_ , hidden_size=3_7 ) def __UpperCamelCase ( self ) -> Any: self.config_tester.run_common_tests() def __UpperCamelCase ( self ) -> Union[str, Any]: _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase_ ) def __UpperCamelCase ( self ) -> Optional[Any]: _a : Tuple = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a : List[str] = type self.model_tester.create_and_check_model(*lowerCamelCase_ ) def __UpperCamelCase ( self ) -> List[Any]: _a , _a : int = self.model_tester.prepare_config_and_inputs_for_common() _a : Optional[Any] = 3 _a : Union[str, Any] = input_dict['input_ids'] _a : List[Any] = input_ids.ne(1 ).to(lowerCamelCase_ ) _a : int = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _a : Any = LlamaForSequenceClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() _a : List[Any] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __UpperCamelCase ( self ) -> List[str]: _a , _a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _a : List[str] = 3 _a : List[str] = 'single_label_classification' _a : Union[str, Any] = input_dict['input_ids'] _a : str = input_ids.ne(1 ).to(lowerCamelCase_ ) _a : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) _a : str = LlamaForSequenceClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() _a : List[Any] = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __UpperCamelCase ( self ) -> Tuple: _a , _a : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() _a : Union[str, Any] = 3 _a : str = 'multi_label_classification' _a : Union[str, Any] = input_dict['input_ids'] _a : Union[str, Any] = input_ids.ne(1 ).to(lowerCamelCase_ ) _a : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) _a : str = LlamaForSequenceClassification(lowerCamelCase_ ) model.to(lowerCamelCase_ ) model.eval() _a : int = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('LLaMA buffers include complex numbers, which breaks this test' ) def __UpperCamelCase ( self ) -> Optional[int]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def __UpperCamelCase ( self , lowerCamelCase_ ) -> List[str]: _a , _a : Dict = self.model_tester.prepare_config_and_inputs_for_common() _a : Union[str, Any] = ids_tensor([1, 1_0] , config.vocab_size ) _a : Optional[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 _a : int = LlamaModel(lowerCamelCase_ ) original_model.to(lowerCamelCase_ ) original_model.eval() _a : str = original_model(lowerCamelCase_ ).last_hidden_state _a : Union[str, Any] = original_model(lowerCamelCase_ ).last_hidden_state set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights _a : Optional[Any] = {'type': scaling_type, 'factor': 10.0} _a : Any = LlamaModel(lowerCamelCase_ ) scaled_model.to(lowerCamelCase_ ) scaled_model.eval() _a : Optional[int] = scaled_model(lowerCamelCase_ ).last_hidden_state _a : int = scaled_model(lowerCamelCase_ ).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(lowerCamelCase_ , lowerCamelCase_ , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(lowerCamelCase_ , lowerCamelCase_ , atol=1e-5 ) ) @require_torch class a ( unittest.TestCase ): '''simple docstring''' @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def __UpperCamelCase ( self ) -> int: _a : Optional[Any] = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] _a : Optional[int] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' ) _a : Tuple = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 _a : List[Any] = torch.tensor([[-6.6550, -4.1227, -4.9859, -3.2406, 0.8262, -3.0033, 1.2964, -3.3699]] ) torch.testing.assert_close(out.mean(-1 ) , lowerCamelCase_ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _a : str = torch.tensor([-12.8281, -7.4453, -0.4639, -8.0625, -7.2500, -8.0000, -6.4883, -7.7695, -7.8438, -7.0312, -6.2188, -7.1328, -1.8496, 1.9961, -8.6250, -6.7227, -12.8281, -6.9492, -7.0742, -7.7852, -7.5820, -7.9062, -6.9375, -7.9805, -8.3438, -8.1562, -8.0469, -7.6250, -7.7422, -7.3398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , lowerCamelCase_ , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def __UpperCamelCase ( self ) -> Optional[int]: _a : Any = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] _a : Any = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' ) _a : List[Any] = model(torch.tensor(lowerCamelCase_ ) ) # Expected mean on dim = -1 _a : Optional[int] = torch.tensor([[-2.0622, -1.2794, -1.1638, -0.9788, -1.4603, -1.0238, -1.7893, -1.4411]] ) torch.testing.assert_close(out.mean(-1 ) , lowerCamelCase_ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _a : List[Any] = torch.tensor([-8.1406, -8.0547, 2.7461, -1.2344, -0.1448, -1.8262, -1.0020, -1.8154, -1.6895, -1.8516, -2.3574, -0.9277, 3.7598, 6.5742, -1.2998, -0.1177, -8.1406, -2.9688, -2.9199, -3.1699, -3.5254, -2.3555, -2.7988, -3.4141, -2.8262, -4.5195, -3.3379, -3.3164, -2.7832, -3.0273] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , lowerCamelCase_ , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' ) @slow def __UpperCamelCase ( self ) -> Any: _a : Optional[int] = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] _a : Union[str, Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' ) _a : str = model(torch.tensor(lowerCamelCase_ ) ) # Expected mean on dim = -1 _a : int = torch.tensor([[-0.8562, -1.8520, -0.7551, -0.4162, -1.5161, -1.2038, -2.4823, -2.3254]] ) torch.testing.assert_close(out.mean(-1 ) , lowerCamelCase_ , atol=1e-2 , rtol=1e-2 ) # slicing logits[0, 0, 0:30] # fmt: off _a : List[Any] = torch.tensor([-2.2227, 4.8828, 0.9023, -0.4578, -0.7871, -0.1033, -0.6221, -0.5786, -0.7803, -1.0674, -1.2920, -0.1570, 0.8008, 2.0723, -0.9497, 0.2771, -2.2227, -0.7612, -1.4346, -1.2061, -1.6426, -0.3000, -0.7139, -1.1934, -1.8691, -1.6973, -1.5947, -1.2705, -0.3523, -0.5513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , lowerCamelCase_ , atol=1e-2 , rtol=1e-2 ) @unittest.skip( 'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' ) @slow def __UpperCamelCase ( self ) -> Dict: _a : Dict = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] _a : str = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' ) _a : Dict = model(torch.tensor(lowerCamelCase_ ) ) _a : str = torch.tensor( [[-4.2327, -3.3360, -4.6665, -4.7631, -1.8180, -3.4170, -1.4211, -3.1810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , lowerCamelCase_ , atol=1e-2 , rtol=1e-2 ) # fmt: off _a : Any = torch.tensor([-9.4922, -3.9551, 1.7998, -5.6758, -5.1055, -5.8984, -4.8320, -6.8086, -6.5391, -5.6172, -5.5820, -5.5352, 1.7881, 3.6289, -6.5117, -3.4785, -9.5000, -6.0352, -6.8125, -6.0195, -6.6836, -5.4727, -6.2812, -6.0391, -7.3398, -7.4297, -7.4844, -6.5820, -5.8789, -5.5312] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , lowerCamelCase_ , atol=1e-5 , rtol=1e-5 ) @unittest.skip('Model is curently gated' ) @slow def __UpperCamelCase ( self ) -> Optional[Any]: _a : List[Any] = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi' _a : List[Any] = 'Simply put, the theory of relativity states that ' _a : List[Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' ) _a : Any = tokenizer.encode(lowerCamelCase_ , return_tensors='pt' ) _a : Union[str, Any] = LlamaForCausalLM.from_pretrained( 'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=lowerCamelCase_ ) # greedy generation outputs _a : List[Any] = model.generate(lowerCamelCase_ , max_new_tokens=6_4 , top_p=lowerCamelCase_ , temperature=1 , do_sample=lowerCamelCase_ ) _a : Dict = tokenizer.decode(generated_ids[0] , skip_special_tokens=lowerCamelCase_ ) self.assertEqual(lowerCamelCase_ , lowerCamelCase_ )
120
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING snake_case__ = logging.get_logger(__name__) snake_case__ = { 'salesforce/blip2-opt-2.7b': 'https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json', } class UpperCamelCase ( __lowercase ): '''simple docstring''' A_ = 'blip_2_vision_model' def __init__( self , A_=14_08 , A_=61_44 , A_=39 , A_=16 , A_=2_24 , A_=14 , A_="gelu" , A_=0.00001 , A_=0.0 , A_=1E-1_0 , A_=True , **A_ , ) -> int: """simple docstring""" super().__init__(**A_ ) _lowerCamelCase = hidden_size _lowerCamelCase = intermediate_size _lowerCamelCase = num_hidden_layers _lowerCamelCase = num_attention_heads _lowerCamelCase = patch_size _lowerCamelCase = image_size _lowerCamelCase = initializer_range _lowerCamelCase = attention_dropout _lowerCamelCase = layer_norm_eps _lowerCamelCase = hidden_act _lowerCamelCase = qkv_bias @classmethod def UpperCamelCase_ ( cls , A_ , **A_ ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(A_ ) _lowerCamelCase , _lowerCamelCase = cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": _lowerCamelCase = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCamelCase ( __lowercase ): '''simple docstring''' A_ = 'blip_2_qformer' def __init__( self , A_=3_05_22 , A_=7_68 , A_=12 , A_=12 , A_=30_72 , A_="gelu" , A_=0.1 , A_=0.1 , A_=5_12 , A_=0.02 , A_=1E-1_2 , A_=0 , A_="absolute" , A_=2 , A_=14_08 , **A_ , ) -> Union[str, Any]: """simple docstring""" super().__init__(pad_token_id=A_ , **A_ ) _lowerCamelCase = vocab_size _lowerCamelCase = hidden_size _lowerCamelCase = num_hidden_layers _lowerCamelCase = num_attention_heads _lowerCamelCase = hidden_act _lowerCamelCase = intermediate_size _lowerCamelCase = hidden_dropout_prob _lowerCamelCase = attention_probs_dropout_prob _lowerCamelCase = max_position_embeddings _lowerCamelCase = initializer_range _lowerCamelCase = layer_norm_eps _lowerCamelCase = position_embedding_type _lowerCamelCase = cross_attention_frequency _lowerCamelCase = encoder_hidden_size @classmethod def UpperCamelCase_ ( cls , A_ , **A_ ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(A_ ) _lowerCamelCase , _lowerCamelCase = cls.get_config_dict(A_ , **A_ ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": _lowerCamelCase = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A_ , **A_ ) class UpperCamelCase ( __lowercase ): '''simple docstring''' A_ = 'blip-2' A_ = True def __init__( self , A_=None , A_=None , A_=None , A_=32 , **A_ ) -> str: """simple docstring""" super().__init__(**A_ ) if vision_config is None: _lowerCamelCase = {} logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' ) if qformer_config is None: _lowerCamelCase = {} logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' ) if text_config is None: _lowerCamelCase = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) _lowerCamelCase = BlipaVisionConfig(**A_ ) _lowerCamelCase = BlipaQFormerConfig(**A_ ) _lowerCamelCase = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' _lowerCamelCase = CONFIG_MAPPING[text_model_type](**A_ ) _lowerCamelCase = self.text_config.tie_word_embeddings _lowerCamelCase = self.text_config.is_encoder_decoder _lowerCamelCase = num_query_tokens _lowerCamelCase = self.vision_config.hidden_size _lowerCamelCase = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES _lowerCamelCase = 1.0 _lowerCamelCase = 0.02 @classmethod def UpperCamelCase_ ( cls , A_ , A_ , A_ , **A_ , ) -> Tuple: """simple docstring""" return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A_ , ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" _lowerCamelCase = copy.deepcopy(self.__dict__ ) _lowerCamelCase = self.vision_config.to_dict() _lowerCamelCase = self.qformer_config.to_dict() _lowerCamelCase = self.text_config.to_dict() _lowerCamelCase = self.__class__.model_type return output
638
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = '''| <pad> <unk> <s> </s> a b c d e f g h i j k'''.split() _lowerCamelCase = dict(zip(A_ , range(len(A_ ) ) ) ) _lowerCamelCase = { '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>''', } _lowerCamelCase = { '''feature_size''': 1, '''padding_value''': 0.0, '''sampling_rate''': 1_60_00, '''return_attention_mask''': False, '''do_normalize''': True, } _lowerCamelCase = tempfile.mkdtemp() _lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) _lowerCamelCase = os.path.join(self.tmpdirname , A_ ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A_ ) + '''\n''' ) with open(self.feature_extraction_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A_ ) + '''\n''' ) # load decoder from hub _lowerCamelCase = '''hf-internal-testing/ngram-beam-search-decoder''' def UpperCamelCase_ ( self , **A_ ) -> str: """simple docstring""" _lowerCamelCase = self.add_kwargs_tokens_map.copy() kwargs.update(A_ ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase_ ( self , **A_ ) -> Optional[Any]: """simple docstring""" return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **A_ ) def UpperCamelCase_ ( self , **A_ ) -> int: """simple docstring""" return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCamelCase_ ( self ) -> Any: """simple docstring""" _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) processor.save_pretrained(self.tmpdirname ) _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , A_ ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , A_ ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , A_ ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(['''xx'''] ) with self.assertRaisesRegex(A_ , '''include''' ): WavaVecaProcessorWithLM( tokenizer=A_ , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = floats_list((3, 10_00) ) _lowerCamelCase = feature_extractor(A_ , return_tensors='''np''' ) _lowerCamelCase = processor(A_ , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = '''This is a test string''' _lowerCamelCase = processor(text=A_ ) _lowerCamelCase = tokenizer(A_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCamelCase_ ( self , A_=(2, 10, 16) , A_=77 ) -> Optional[Any]: """simple docstring""" np.random.seed(A_ ) return np.random.rand(*A_ ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits(shape=(10, 16) , seed=13 ) _lowerCamelCase = processor.decode(A_ ) _lowerCamelCase = decoder.decode_beams(A_ )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual('''</s> <s> </s>''' , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ['''fork'''], ['''spawn''']] ) def UpperCamelCase_ ( self , A_ ) -> int: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: _lowerCamelCase = processor.batch_decode(A_ ) else: with get_context(A_ ).Pool() as pool: _lowerCamelCase = processor.batch_decode(A_ , A_ ) _lowerCamelCase = list(A_ ) with get_context('''fork''' ).Pool() as p: _lowerCamelCase = decoder.decode_beams_batch(A_ , A_ ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(A_ , decoded_processor.text ) self.assertListEqual(['''<s> <s> </s>''', '''<s> <s> <s>'''] , decoded_processor.text ) self.assertListEqual(A_ , decoded_processor.logit_score ) self.assertListEqual(A_ , decoded_processor.lm_score ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = 15 _lowerCamelCase = -20.0 _lowerCamelCase = -4.0 _lowerCamelCase = processor.batch_decode( A_ , beam_width=A_ , beam_prune_logp=A_ , token_min_logp=A_ , ) _lowerCamelCase = decoded_processor_out.text _lowerCamelCase = list(A_ ) with get_context('''fork''' ).Pool() as pool: _lowerCamelCase = decoder.decode_beams_batch( A_ , A_ , beam_width=A_ , beam_prune_logp=A_ , token_min_logp=A_ , ) _lowerCamelCase = [d[0][0] for d in decoded_decoder_out] _lowerCamelCase = [d[0][2] for d in decoded_decoder_out] _lowerCamelCase = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(A_ , A_ ) self.assertListEqual(['''</s> <s> <s>''', '''<s> <s> <s>'''] , A_ ) self.assertTrue(np.array_equal(A_ , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , A_ , atol=1E-3 ) ) self.assertTrue(np.array_equal(A_ , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9474] , A_ , atol=1E-3 ) ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = 2.0 _lowerCamelCase = 5.0 _lowerCamelCase = -20.0 _lowerCamelCase = True _lowerCamelCase = processor.batch_decode( A_ , alpha=A_ , beta=A_ , unk_score_offset=A_ , lm_score_boundary=A_ , ) _lowerCamelCase = decoded_processor_out.text _lowerCamelCase = list(A_ ) decoder.reset_params( alpha=A_ , beta=A_ , unk_score_offset=A_ , lm_score_boundary=A_ , ) with get_context('''fork''' ).Pool() as pool: _lowerCamelCase = decoder.decode_beams_batch( A_ , A_ , ) _lowerCamelCase = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(A_ , A_ ) self.assertListEqual(['''<s> </s> <s> </s> </s>''', '''</s> </s> <s> </s> </s>'''] , A_ ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] _lowerCamelCase = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() _lowerCamelCase = os.listdir(A_ ) _lowerCamelCase = ['''alphabet.json''', '''language_model'''] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(A_ , A_ ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = snapshot_download('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained(A_ ) _lowerCamelCase = processor.decoder.model_container[processor.decoder._model_key] _lowerCamelCase = Path(language_model._kenlm_model.path.decode('''utf-8''' ) ).parent.parent.absolute() _lowerCamelCase = os.listdir(A_ ) _lowerCamelCase = os.listdir(A_ ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(A_ , A_ ) def UpperCamelCase_ ( self ) -> int: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = AutoProcessor.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = floats_list((3, 10_00) ) _lowerCamelCase = processor_wavaveca(A_ , return_tensors='''np''' ) _lowerCamelCase = processor_auto(A_ , return_tensors='''np''' ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = processor_wavaveca.batch_decode(A_ ) _lowerCamelCase = processor_auto.batch_decode(A_ ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" _lowerCamelCase = self.get_feature_extractor() _lowerCamelCase = self.get_tokenizer() _lowerCamelCase = self.get_decoder() _lowerCamelCase = WavaVecaProcessorWithLM(tokenizer=A_ , feature_extractor=A_ , decoder=A_ ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , ) @staticmethod def UpperCamelCase_ ( A_ , A_ ) -> str: """simple docstring""" _lowerCamelCase = [d[key] for d in offsets] return retrieved_list def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = self._get_dummy_logits()[0] _lowerCamelCase = processor.decode(A_ , output_word_offsets=A_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('''text''' in outputs ) self.assertTrue('''word_offsets''' in outputs ) self.assertTrue(isinstance(A_ , A_ ) ) self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''start_offset''' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''] , '''end_offset''' ) , [1, 3, 5] ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" _lowerCamelCase = WavaVecaProcessorWithLM.from_pretrained('''hf-internal-testing/processor_with_lm''' ) _lowerCamelCase = self._get_dummy_logits() _lowerCamelCase = processor.batch_decode(A_ , output_word_offsets=A_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue('''text''' in outputs ) self.assertTrue('''word_offsets''' in outputs ) self.assertTrue(isinstance(A_ , A_ ) ) self.assertListEqual( [''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) for o in outputs['''word_offsets''']] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''word''' ) , ['''<s>''', '''<s>''', '''</s>'''] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''start_offset''' ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs['''word_offsets'''][0] , '''end_offset''' ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def UpperCamelCase_ ( self ) -> List[Any]: """simple docstring""" import torch _lowerCamelCase = load_dataset('''common_voice''' , '''en''' , split='''train''' , streaming=A_ ) _lowerCamelCase = ds.cast_column('''audio''' , datasets.Audio(sampling_rate=1_60_00 ) ) _lowerCamelCase = iter(A_ ) _lowerCamelCase = next(A_ ) _lowerCamelCase = AutoProcessor.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) _lowerCamelCase = WavaVecaForCTC.from_pretrained('''patrickvonplaten/wav2vec2-base-100h-with-lm''' ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train _lowerCamelCase = processor(sample['''audio''']['''array'''] , return_tensors='''pt''' ).input_values with torch.no_grad(): _lowerCamelCase = model(A_ ).logits.cpu().numpy() _lowerCamelCase = processor.decode(logits[0] , output_word_offsets=A_ ) _lowerCamelCase = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate _lowerCamelCase = [ { '''start_time''': d['''start_offset'''] * time_offset, '''end_time''': d['''end_offset'''] * time_offset, '''word''': d['''word'''], } for d in output['''word_offsets'''] ] _lowerCamelCase = '''WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL''' # output words self.assertEqual(''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) , A_ ) self.assertEqual(''' '''.join(self.get_from_offsets(A_ , '''word''' ) ) , output.text ) # output times _lowerCamelCase = torch.tensor(self.get_from_offsets(A_ , '''start_time''' ) ) _lowerCamelCase = torch.tensor(self.get_from_offsets(A_ , '''end_time''' ) ) # fmt: off _lowerCamelCase = torch.tensor([1.4199, 1.6599, 2.2599, 3.0, 3.24, 3.5999, 3.7999, 4.0999, 4.26, 4.94, 5.28, 5.6599, 5.78, 5.94, 6.32, 6.5399, 6.6599] ) _lowerCamelCase = torch.tensor([1.5399, 1.8999, 2.9, 3.16, 3.5399, 3.72, 4.0199, 4.1799, 4.76, 5.1599, 5.5599, 5.6999, 5.86, 6.1999, 6.38, 6.6199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(A_ , A_ , atol=0.01 ) ) self.assertTrue(torch.allclose(A_ , A_ , atol=0.01 ) )
638
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process A_ = logging.getLogger(__name__) @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE_ = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) SCREAMING_SNAKE_CASE_ = field( default=__lowercase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) SCREAMING_SNAKE_CASE_ = field( default='NER' , metadata={'help': 'Task type to fine tune in training (e.g. NER, POS, etc)'} ) SCREAMING_SNAKE_CASE_ = field( default=__lowercase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) SCREAMING_SNAKE_CASE_ = field(default=__lowercase , 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. SCREAMING_SNAKE_CASE_ = field( default=__lowercase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class UpperCAmelCase : '''simple docstring''' SCREAMING_SNAKE_CASE_ = field( metadata={'help': 'The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task.'} ) SCREAMING_SNAKE_CASE_ = field( default=__lowercase , metadata={'help': 'Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.'} , ) SCREAMING_SNAKE_CASE_ = field( default=1_28 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) SCREAMING_SNAKE_CASE_ = field( default=__lowercase , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def _UpperCamelCase ( ) -> int: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowerCamelCase_ = 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. lowerCamelCase_ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCamelCase_ = 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.' ) lowerCamelCase_ = import_module('tasks' ) try: lowerCamelCase_ = getattr(__A ,model_args.task_type ) lowerCamelCase_ = token_classification_task_clazz() except AttributeError: raise ValueError( f'''Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ''' f'''Available tasks classes are: {TokenClassificationTask.__subclasses__()}''' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' ,datefmt='%m/%d/%Y %H:%M:%S' ,level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN ,) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' ,training_args.local_rank ,training_args.device ,training_args.n_gpu ,bool(training_args.local_rank != -1 ) ,training_args.fpaa ,) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' ,__A ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCamelCase_ = token_classification_task.get_labels(data_args.labels ) lowerCamelCase_ = dict(enumerate(__A ) ) lowerCamelCase_ = len(__A ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase_ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path ,num_labels=__A ,idalabel=__A ,labelaid={label: i for i, label in enumerate(__A )} ,cache_dir=model_args.cache_dir ,) lowerCamelCase_ = 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 ,use_fast=model_args.use_fast ,) lowerCamelCase_ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path ,from_tf=bool('.ckpt' in model_args.model_name_or_path ) ,config=__A ,cache_dir=model_args.cache_dir ,) # Get datasets lowerCamelCase_ = ( TokenClassificationDataset( token_classification_task=__A ,data_dir=data_args.data_dir ,tokenizer=__A ,labels=__A ,model_type=config.model_type ,max_seq_length=data_args.max_seq_length ,overwrite_cache=data_args.overwrite_cache ,mode=Split.train ,) if training_args.do_train else None ) lowerCamelCase_ = ( TokenClassificationDataset( token_classification_task=__A ,data_dir=data_args.data_dir ,tokenizer=__A ,labels=__A ,model_type=config.model_type ,max_seq_length=data_args.max_seq_length ,overwrite_cache=data_args.overwrite_cache ,mode=Split.dev ,) if training_args.do_eval else None ) def align_predictions(__UpperCamelCase ,__UpperCamelCase ) -> Tuple[List[int], List[int]]: lowerCamelCase_ = np.argmax(__A ,axis=2 ) lowerCamelCase_ = preds.shape lowerCamelCase_ = [[] for _ in range(__A )] lowerCamelCase_ = [[] for _ in range(__A )] for i in range(__A ): for j in range(__A ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(__UpperCamelCase ) -> Dict: lowerCamelCase_ = align_predictions(p.predictions ,p.label_ids ) return { "accuracy_score": accuracy_score(__A ,__A ), "precision": precision_score(__A ,__A ), "recall": recall_score(__A ,__A ), "f1": fa_score(__A ,__A ), } # Data collator lowerCamelCase_ = DataCollatorWithPadding(__A ,pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCamelCase_ = Trainer( model=__A ,args=__A ,train_dataset=__A ,eval_dataset=__A ,compute_metrics=__A ,data_collator=__A ,) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCamelCase_ = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) lowerCamelCase_ = trainer.evaluate() lowerCamelCase_ = os.path.join(training_args.output_dir ,'eval_results.txt' ) if trainer.is_world_process_zero(): with open(__A ,'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' ,__A ,__A ) writer.write('%s = %s\n' % (key, value) ) results.update(__A ) # Predict if training_args.do_predict: lowerCamelCase_ = TokenClassificationDataset( token_classification_task=__A ,data_dir=data_args.data_dir ,tokenizer=__A ,labels=__A ,model_type=config.model_type ,max_seq_length=data_args.max_seq_length ,overwrite_cache=data_args.overwrite_cache ,mode=Split.test ,) lowerCamelCase_ = trainer.predict(__A ) lowerCamelCase_ = align_predictions(__A ,__A ) lowerCamelCase_ = os.path.join(training_args.output_dir ,'test_results.txt' ) if trainer.is_world_process_zero(): with open(__A ,'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' ,__A ,__A ) writer.write('%s = %s\n' % (key, value) ) # Save predictions lowerCamelCase_ = os.path.join(training_args.output_dir ,'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(__A ,'w' ) as writer: with open(os.path.join(data_args.data_dir ,'test.txt' ) ,'r' ) as f: token_classification_task.write_predictions_to_file(__A ,__A ,__A ) return results def _UpperCamelCase ( __UpperCamelCase ) -> List[Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
42
import tensorflow as tf from ...tf_utils import shape_list class A_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , _A , _A , _A , _A , _A=1 , _A=False , **_A) -> Union[str, Any]: """simple docstring""" super().__init__(**_A) _UpperCAmelCase : Dict = vocab_size _UpperCAmelCase : Any = d_embed _UpperCAmelCase : List[Any] = d_proj _UpperCAmelCase : List[Any] = cutoffs + [vocab_size] _UpperCAmelCase : str = [0] + self.cutoffs _UpperCAmelCase : Union[str, Any] = div_val _UpperCAmelCase : Any = self.cutoffs[0] _UpperCAmelCase : Optional[Any] = len(self.cutoffs) - 1 _UpperCAmelCase : Tuple = self.shortlist_size + self.n_clusters _UpperCAmelCase : List[Any] = keep_order _UpperCAmelCase : List[str] = [] _UpperCAmelCase : List[Any] = [] def snake_case__ ( self , _A) -> List[str]: """simple docstring""" if self.n_clusters > 0: _UpperCAmelCase : Union[str, Any] = self.add_weight( shape=(self.n_clusters, self.d_embed) , initializer='''zeros''' , trainable=_A , name='''cluster_weight''') _UpperCAmelCase : Tuple = self.add_weight( shape=(self.n_clusters,) , initializer='''zeros''' , trainable=_A , name='''cluster_bias''') if self.div_val == 1: for i in range(len(self.cutoffs)): if self.d_proj != self.d_embed: _UpperCAmelCase : Optional[int] = self.add_weight( shape=(self.d_embed, self.d_proj) , initializer='''zeros''' , trainable=_A , name=f'''out_projs_._{i}''' , ) self.out_projs.append(_A) else: self.out_projs.append(_A) _UpperCAmelCase : str = self.add_weight( shape=(self.vocab_size, self.d_embed) , initializer='''zeros''' , trainable=_A , name=f'''out_layers_._{i}_._weight''' , ) _UpperCAmelCase : Optional[Any] = self.add_weight( shape=(self.vocab_size,) , initializer='''zeros''' , trainable=_A , name=f'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias)) else: for i in range(len(self.cutoffs)): _UpperCAmelCase , _UpperCAmelCase : str = self.cutoff_ends[i], self.cutoff_ends[i + 1] _UpperCAmelCase : Optional[Any] = self.d_embed // (self.div_val**i) _UpperCAmelCase : Optional[int] = self.add_weight( shape=(d_emb_i, self.d_proj) , initializer='''zeros''' , trainable=_A , name=f'''out_projs_._{i}''') self.out_projs.append(_A) _UpperCAmelCase : Dict = self.add_weight( shape=(r_idx - l_idx, d_emb_i) , initializer='''zeros''' , trainable=_A , name=f'''out_layers_._{i}_._weight''' , ) _UpperCAmelCase : Any = self.add_weight( shape=(r_idx - l_idx,) , initializer='''zeros''' , trainable=_A , name=f'''out_layers_._{i}_._bias''' , ) self.out_layers.append((weight, bias)) super().build(_A) @staticmethod def snake_case__ ( _A , _A , _A , _A=None) -> Optional[int]: """simple docstring""" _UpperCAmelCase : Tuple = x if proj is not None: _UpperCAmelCase : Optional[int] = tf.einsum('''ibd,ed->ibe''' , _A , _A) return tf.einsum('''ibd,nd->ibn''' , _A , _A) + b @staticmethod def snake_case__ ( _A , _A) -> str: """simple docstring""" _UpperCAmelCase : Optional[Any] = shape_list(_A) _UpperCAmelCase : int = tf.range(lp_size[0] , dtype=target.dtype) _UpperCAmelCase : Optional[Any] = tf.stack([r, target] , 1) return tf.gather_nd(_A , _A) def snake_case__ ( self , _A , _A , _A=True , _A=False) -> int: """simple docstring""" _UpperCAmelCase : Tuple = 0 if self.n_clusters == 0: _UpperCAmelCase : int = self._logit(_A , self.out_layers[0][0] , self.out_layers[0][1] , self.out_projs[0]) if target is not None: _UpperCAmelCase : Any = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=_A , logits=_A) _UpperCAmelCase : Union[str, Any] = tf.nn.log_softmax(_A , axis=-1) else: _UpperCAmelCase : Union[str, Any] = shape_list(_A) _UpperCAmelCase : str = [] _UpperCAmelCase : Optional[Any] = tf.zeros(hidden_sizes[:2]) for i in range(len(self.cutoffs)): _UpperCAmelCase , _UpperCAmelCase : Optional[int] = self.cutoff_ends[i], self.cutoff_ends[i + 1] if target is not None: _UpperCAmelCase : Any = (target >= l_idx) & (target < r_idx) _UpperCAmelCase : str = tf.where(_A) _UpperCAmelCase : Union[str, Any] = tf.boolean_mask(_A , _A) - l_idx if self.div_val == 1: _UpperCAmelCase : str = self.out_layers[0][0][l_idx:r_idx] _UpperCAmelCase : Any = self.out_layers[0][1][l_idx:r_idx] else: _UpperCAmelCase : int = self.out_layers[i][0] _UpperCAmelCase : int = self.out_layers[i][1] if i == 0: _UpperCAmelCase : Optional[Any] = tf.concat([cur_W, self.cluster_weight] , 0) _UpperCAmelCase : Optional[int] = tf.concat([cur_b, self.cluster_bias] , 0) _UpperCAmelCase : int = self._logit(_A , _A , _A , self.out_projs[0]) _UpperCAmelCase : int = tf.nn.log_softmax(_A) out.append(head_logprob[..., : self.cutoffs[0]]) if target is not None: _UpperCAmelCase : List[str] = tf.boolean_mask(_A , _A) _UpperCAmelCase : Optional[Any] = self._gather_logprob(_A , _A) else: _UpperCAmelCase : List[str] = self._logit(_A , _A , _A , self.out_projs[i]) _UpperCAmelCase : Union[str, Any] = tf.nn.log_softmax(_A) _UpperCAmelCase : Optional[Any] = self.cutoffs[0] + i - 1 # No probability for the head cluster _UpperCAmelCase : Optional[Any] = head_logprob[..., cluster_prob_idx, None] + tail_logprob out.append(_A) if target is not None: _UpperCAmelCase : Optional[Any] = tf.boolean_mask(_A , _A) _UpperCAmelCase : str = tf.boolean_mask(_A , _A) _UpperCAmelCase : Optional[Any] = self._gather_logprob(_A , _A) cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1] if target is not None: loss += tf.scatter_nd(_A , -cur_logprob , shape_list(_A)) _UpperCAmelCase : Optional[Any] = tf.concat(_A , axis=-1) if target is not None: if return_mean: _UpperCAmelCase : Optional[int] = tf.reduce_mean(_A) # Add the training-time loss value to the layer using `self.add_loss()`. self.add_loss(_A) # Log the loss as a metric (we could log arbitrary metrics, # including different metrics for training and inference. self.add_metric(_A , name=self.name , aggregation='''mean''' if return_mean else '''''') return out
485
0
from random import shuffle import tensorflow as tf from numpy import array def _A ( lowerCamelCase , lowerCamelCase ): a__ : int = int(lowerCamelCase ) assert noofclusters < len(lowerCamelCase ) # Find out the dimensionality a__ : List[str] = len(vectors[0] ) # Will help select random centroids from among the available vectors a__ : List[str] = list(range(len(lowerCamelCase ) ) ) shuffle(lowerCamelCase ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. a__ : Any = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION a__ : Optional[Any] = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points a__ : Union[str, Any] = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(lowerCamelCase ) ] ##These nodes will assign the centroid Variables the appropriate ##values a__ : str = tf.placeholder("float64" , [dim] ) a__ : Optional[int] = [] for centroid in centroids: cent_assigns.append(tf.assign(lowerCamelCase , lowerCamelCase ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) a__ : List[Any] = [tf.Variable(0 ) for i in range(len(lowerCamelCase ) )] ##These nodes will assign an assignment Variable the appropriate ##value a__ : List[str] = tf.placeholder("int32" ) a__ : int = [] for assignment in assignments: cluster_assigns.append(tf.assign(lowerCamelCase , lowerCamelCase ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input a__ : Tuple = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors a__ : List[str] = tf.reduce_mean(lowerCamelCase , 0 ) ##Node for computing Euclidean distances # Placeholders for input a__ : Any = tf.placeholder("float" , [dim] ) a__ : List[Any] = tf.placeholder("float" , [dim] ) a__ : Dict = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowerCamelCase , lowerCamelCase ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input a__ : Optional[int] = tf.placeholder("float" , [noofclusters] ) a__ : int = tf.argmin(lowerCamelCase , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. a__ : Tuple = tf.initialize_all_variables() # Initialize all variables sess.run(lowerCamelCase ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. a__ : Tuple = 100 for _ in range(lowerCamelCase ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(lowerCamelCase ) ): a__ : Tuple = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. a__ : Tuple = [ sess.run(lowerCamelCase , feed_dict={va: vect, va: sess.run(lowerCamelCase )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input a__ : Any = sess.run( lowerCamelCase , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(lowerCamelCase ): # Collect all the vectors assigned to this cluster a__ : List[Any] = [ vectors[i] for i in range(len(lowerCamelCase ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location a__ : Optional[Any] = sess.run( lowerCamelCase , feed_dict={mean_input: array(lowerCamelCase )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments a__ : Optional[int] = sess.run(lowerCamelCase ) a__ : Optional[int] = sess.run(lowerCamelCase ) return centroids, assignments
629
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : str = { """configuration_distilbert""": [ """DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DistilBertConfig""", """DistilBertOnnxConfig""", ], """tokenization_distilbert""": ["""DistilBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = ["""DistilBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ """DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """DistilBertForMaskedLM""", """DistilBertForMultipleChoice""", """DistilBertForQuestionAnswering""", """DistilBertForSequenceClassification""", """DistilBertForTokenClassification""", """DistilBertModel""", """DistilBertPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ """TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFDistilBertForMaskedLM""", """TFDistilBertForMultipleChoice""", """TFDistilBertForQuestionAnswering""", """TFDistilBertForSequenceClassification""", """TFDistilBertForTokenClassification""", """TFDistilBertMainLayer""", """TFDistilBertModel""", """TFDistilBertPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ """FlaxDistilBertForMaskedLM""", """FlaxDistilBertForMultipleChoice""", """FlaxDistilBertForQuestionAnswering""", """FlaxDistilBertForSequenceClassification""", """FlaxDistilBertForTokenClassification""", """FlaxDistilBertModel""", """FlaxDistilBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
629
1
"""simple docstring""" def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : str , _UpperCAmelCase : int ): lowerCAmelCase = word.split() def justify(_UpperCAmelCase : list , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> str: lowerCAmelCase = max_width - width lowerCAmelCase = len(_UpperCAmelCase ) if len(_UpperCAmelCase ) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: lowerCAmelCase = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] lowerCAmelCase = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] lowerCAmelCase = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(_UpperCAmelCase ): num_spaces_between_words_list[i] += 1 lowerCAmelCase = [] for i in range(_UpperCAmelCase ): # add the word aligned_words_list.append(line[i] ) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * ' ' ) # just add the last word to the sentence aligned_words_list.append(line[-1] ) # join the aligned words list to form a justified line return "".join(_UpperCAmelCase ) lowerCAmelCase = [] lowerCAmelCase = [] lowerCAmelCase = 0 for word in words: if width + len(_UpperCAmelCase ) + len(_UpperCAmelCase ) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(_UpperCAmelCase ) width += len(_UpperCAmelCase ) else: # justify the line and add it to result answer.append(justify(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) ) # reset new line and new width lowerCAmelCase ,lowerCAmelCase = [word], len(_UpperCAmelCase ) lowerCAmelCase = max_width - width - len(_UpperCAmelCase ) answer.append(' '.join(_UpperCAmelCase ) + (remaining_spaces + 1) * ' ' ) return answer if __name__ == "__main__": from doctest import testmod testmod()
4
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available UpperCAmelCase__ = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = ['''BartphoTokenizer'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys UpperCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
186
0
import sys def lowerCAmelCase_ ( A_): UpperCamelCase__: Union[str, Any] = len(A_) UpperCamelCase__: Tuple = [[0 for x in range(A_)] for x in range(A_)] UpperCamelCase__: int = [[0 for x in range(A_)] for x in range(A_)] for chain_length in range(2 ,A_): for a in range(1 ,n - chain_length + 1): UpperCamelCase__: int = a + chain_length - 1 UpperCamelCase__: Tuple = sys.maxsize for c in range(A_ ,A_): UpperCamelCase__: Tuple = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: UpperCamelCase__: List[Any] = cost UpperCamelCase__: int = c return matrix, sol def lowerCAmelCase_ ( A_ ,A_ ,A_): if i == j: print("A" + str(A_) ,end=" ") else: print("(" ,end=" ") print_optiomal_solution(A_ ,A_ ,optimal_solution[i][j]) print_optiomal_solution(A_ ,optimal_solution[i][j] + 1 ,A_) print(")" ,end=" ") def lowerCAmelCase_ ( ): UpperCamelCase__: Any = [30, 35, 15, 5, 10, 20, 25] UpperCamelCase__: Optional[Any] = len(A_) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 UpperCamelCase__ , UpperCamelCase__: int = matrix_chain_order(A_) print("No. of Operation required: " + str(matrix[1][n - 1])) print_optiomal_solution(A_ ,1 ,n - 1) if __name__ == "__main__": main()
221
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin A__: str = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right A__: int = 25_0004 A__: Optional[Any] = 25_0020 @require_sentencepiece @require_tokenizers class _a ( UpperCamelCase__ , unittest.TestCase): """simple docstring""" UpperCamelCase__ = MBartaaTokenizer UpperCamelCase__ = MBartaaTokenizerFast UpperCamelCase__ = True UpperCamelCase__ = True def UpperCAmelCase_ ( self: str ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase__: Tuple = MBartaaTokenizer(__lowerCamelCase , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=__lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self: Dict ): '''simple docstring''' UpperCamelCase__: Union[str, Any] = "<s>" UpperCamelCase__: Dict = 0 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: Dict ): '''simple docstring''' UpperCamelCase__: Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(__lowerCamelCase ) , 1054 ) def UpperCAmelCase_ ( self: Tuple ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1054 ) def UpperCAmelCase_ ( self: List[Any] ): '''simple docstring''' UpperCamelCase__: Tuple = MBartaaTokenizer(__lowerCamelCase , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=__lowerCamelCase ) UpperCamelCase__: Optional[Any] = 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]] , ) UpperCamelCase__: List[str] = 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__: Any = 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] ] , ) UpperCamelCase__: Tuple = 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>", "."] , ) @slow def UpperCAmelCase_ ( self: List[Any] ): '''simple docstring''' UpperCamelCase__: str = {"input_ids": [[25_0004, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [25_0004, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_0004, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=__lowerCamelCase , model_name="facebook/mbart-large-50" , revision="d3913889c59cd5c9e456b269c376325eabad57e2" , ) def UpperCAmelCase_ ( self: Dict ): '''simple docstring''' 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 UpperCamelCase__: Tuple = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart50", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__: Optional[Any] = self.rust_tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) UpperCamelCase__: Optional[int] = self.tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) UpperCamelCase__: int = tempfile.mkdtemp() UpperCamelCase__: List[Any] = tokenizer_r.save_pretrained(__lowerCamelCase ) UpperCamelCase__: Optional[int] = tokenizer_p.save_pretrained(__lowerCamelCase ) # 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 ) ) UpperCamelCase__: str = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(__lowerCamelCase , __lowerCamelCase ) # Checks everything loads correctly in the same way UpperCamelCase__: Dict = tokenizer_r.from_pretrained(__lowerCamelCase ) UpperCamelCase__: List[str] = tokenizer_p.from_pretrained(__lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__lowerCamelCase , __lowerCamelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__lowerCamelCase ) # Save tokenizer rust, legacy_format=True UpperCamelCase__: List[Any] = tempfile.mkdtemp() UpperCamelCase__: Dict = tokenizer_r.save_pretrained(__lowerCamelCase , legacy_format=__lowerCamelCase ) UpperCamelCase__: Union[str, Any] = tokenizer_p.save_pretrained(__lowerCamelCase ) # Checks it save with the same files self.assertSequenceEqual(__lowerCamelCase , __lowerCamelCase ) # Checks everything loads correctly in the same way UpperCamelCase__: Optional[Any] = tokenizer_r.from_pretrained(__lowerCamelCase ) UpperCamelCase__: int = tokenizer_p.from_pretrained(__lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__lowerCamelCase , __lowerCamelCase ) ) shutil.rmtree(__lowerCamelCase ) # Save tokenizer rust, legacy_format=False UpperCamelCase__: Any = tempfile.mkdtemp() UpperCamelCase__: Any = tokenizer_r.save_pretrained(__lowerCamelCase , legacy_format=__lowerCamelCase ) UpperCamelCase__: Any = tokenizer_p.save_pretrained(__lowerCamelCase ) # 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 UpperCamelCase__: Tuple = tokenizer_r.from_pretrained(__lowerCamelCase ) UpperCamelCase__: List[str] = tokenizer_p.from_pretrained(__lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__lowerCamelCase , __lowerCamelCase ) ) shutil.rmtree(__lowerCamelCase ) @require_torch @require_sentencepiece @require_tokenizers class _a ( unittest.TestCase): """simple docstring""" UpperCamelCase__ = """facebook/mbart-large-50-one-to-many-mmt""" UpperCamelCase__ = [ """ 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.""", ] UpperCamelCase__ = [ """Ş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.""", ] UpperCamelCase__ = [EN_CODE, 8274, 12_7873, 2_5916, 7, 8622, 2071, 438, 6_7485, 53, 18_7895, 23, 5_1712, 2] @classmethod def UpperCAmelCase_ ( cls: Union[str, Any] ): '''simple docstring''' UpperCamelCase__: MBartaaTokenizer = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) UpperCamelCase__: Union[str, Any] = 1 return cls def UpperCAmelCase_ ( self: Tuple ): '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 25_0001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 25_0004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 25_0020 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["mr_IN"] , 25_0038 ) def UpperCAmelCase_ ( self: Any ): '''simple docstring''' UpperCamelCase__: Optional[int] = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __lowerCamelCase ) def UpperCAmelCase_ ( self: Optional[int] ): '''simple docstring''' self.assertIn(__lowerCamelCase , self.tokenizer.all_special_ids ) UpperCamelCase__: List[Any] = [RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] UpperCamelCase__: List[Any] = self.tokenizer.decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) UpperCamelCase__: List[Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertNotIn(self.tokenizer.eos_token , __lowerCamelCase ) def UpperCAmelCase_ ( self: Optional[int] ): '''simple docstring''' UpperCamelCase__: List[str] = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , __lowerCamelCase ) UpperCamelCase__: List[str] = 10 UpperCamelCase__: List[Any] = self.tokenizer(__lowerCamelCase , max_length=__lowerCamelCase , truncation=__lowerCamelCase ).input_ids[0] self.assertEqual(ids[0] , __lowerCamelCase ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) def UpperCAmelCase_ ( self: List[Any] ): '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [25_0053, 25_0001] ) def UpperCAmelCase_ ( self: Optional[int] ): '''simple docstring''' UpperCamelCase__: List[Any] = tempfile.mkdtemp() UpperCamelCase__: List[Any] = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__lowerCamelCase ) UpperCamelCase__: Tuple = MBartaaTokenizer.from_pretrained(__lowerCamelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __lowerCamelCase ) @require_torch def UpperCAmelCase_ ( self: Tuple ): '''simple docstring''' UpperCamelCase__: int = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__lowerCamelCase , return_tensors="pt" ) UpperCamelCase__: Optional[Any] = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def UpperCAmelCase_ ( self: Optional[int] ): '''simple docstring''' UpperCamelCase__: str = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) UpperCamelCase__: List[str] = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) UpperCamelCase__: List[Any] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __lowerCamelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase_ ( self: int ): '''simple docstring''' UpperCamelCase__: Optional[int] = self.tokenizer(self.src_text , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=3 , return_tensors="pt" ) UpperCamelCase__: List[str] = self.tokenizer( text_target=self.tgt_text , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=10 , return_tensors="pt" ) UpperCamelCase__: Tuple = targets["input_ids"] UpperCamelCase__: int = shift_tokens_right(__lowerCamelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase_ ( self: List[str] ): '''simple docstring''' UpperCamelCase__: Dict = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(__lowerCamelCase ) , { # en_XX, A, test, EOS "input_ids": [[25_0004, 62, 3034, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 25_0001, } , )
221
1
'''simple docstring''' def A_ ( _lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : int = len(_lowerCAmelCase ) _lowerCamelCase : Dict = sum(_lowerCAmelCase ) _lowerCamelCase : List[Any] = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): _lowerCamelCase : Optional[Any] = True for i in range(1 , s + 1 ): _lowerCamelCase : Optional[int] = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): _lowerCamelCase : Tuple = dp[i][j - 1] if arr[i - 1] <= j: _lowerCamelCase : Optional[Any] = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: _lowerCamelCase : int = s - 2 * j break return diff
44
"""simple docstring""" import unittest from transformers import AutoTokenizer, NystromformerConfig, 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 ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : def __init__( self , snake_case__ , snake_case__=13 , snake_case__=7 , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=True , snake_case__=99 , snake_case__=32 , snake_case__=5 , snake_case__=4 , snake_case__=37 , snake_case__="gelu" , snake_case__=0.1 , snake_case__=0.1 , snake_case__=5_12 , snake_case__=16 , snake_case__=2 , snake_case__=0.02 , snake_case__=3 , snake_case__=4 , snake_case__=None , ) -> int: """simple docstring""" UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = seq_length UpperCAmelCase = is_training UpperCAmelCase = use_input_mask UpperCAmelCase = use_token_type_ids UpperCAmelCase = use_labels UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = type_sequence_label_size UpperCAmelCase = initializer_range UpperCAmelCase = num_labels UpperCAmelCase = num_choices UpperCAmelCase = scope def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = None if self.use_token_type_ids: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" return NystromformerConfig( 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=snake_case__ , initializer_range=self.initializer_range , ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> List[str]: """simple docstring""" UpperCAmelCase = NystromformerModel(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ ) UpperCAmelCase = model(snake_case__ , token_type_ids=snake_case__ ) UpperCAmelCase = model(snake_case__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> int: """simple docstring""" UpperCAmelCase = NystromformerForMaskedLM(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = NystromformerForQuestionAnswering(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , start_positions=snake_case__ , end_positions=snake_case__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = NystromformerForSequenceClassification(snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> int: """simple docstring""" UpperCAmelCase = self.num_labels UpperCAmelCase = NystromformerForTokenClassification(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = model(snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Dict: """simple docstring""" UpperCAmelCase = self.num_choices UpperCAmelCase = NystromformerForMultipleChoice(config=snake_case__ ) model.to(snake_case__ ) model.eval() UpperCAmelCase = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase = model( snake_case__ , attention_mask=snake_case__ , token_type_ids=snake_case__ , labels=snake_case__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = self.prepare_config_and_inputs() ( ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ( UpperCAmelCase ) , ) = config_and_inputs UpperCAmelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( a_ , a_ , unittest.TestCase ): _A : Optional[Any] = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) _A : Optional[Any] = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) _A : int = False _A : Dict = False def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = NystromformerModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=snake_case__ , hidden_size=37 ) def UpperCamelCase_ ( self ) -> str: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> Dict: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase = type self.model_tester.create_and_check_model(*snake_case__ ) def UpperCamelCase_ ( self ) -> Optional[Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case__ ) def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case__ ) def UpperCamelCase_ ( self ) -> Tuple: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case__ ) def UpperCamelCase_ ( self ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case__ ) def UpperCamelCase_ ( self ) -> Optional[int]: """simple docstring""" UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case__ ) @slow def UpperCamelCase_ ( self ) -> int: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase = NystromformerModel.from_pretrained(snake_case__ ) self.assertIsNotNone(snake_case__ ) @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def UpperCamelCase_ ( self ) -> List[str]: """simple docstring""" UpperCAmelCase = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): UpperCAmelCase = model(snake_case__ )[0] UpperCAmelCase = torch.Size((1, 6, 7_68) ) self.assertEqual(output.shape , snake_case__ ) UpperCAmelCase = torch.tensor( [[[-0.4_532, -0.0_936, 0.5_137], [-0.2_676, 0.0_628, 0.6_186], [-0.3_629, -0.1_726, 0.4_716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case__ , atol=1e-4 ) ) @slow def UpperCamelCase_ ( self ) -> Any: """simple docstring""" UpperCAmelCase = """the [MASK] of Belgium is Brussels""" UpperCAmelCase = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" ) UpperCAmelCase = tokenizer(snake_case__ , return_tensors="""pt""" ) with torch.no_grad(): UpperCAmelCase = model(encoding.input_ids ).logits UpperCAmelCase = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(snake_case__ ) , """capital""" )
673
0
import argparse import os import torch from transformers.utils import WEIGHTS_NAME _lowercase : List[str] =['''small''', '''medium''', '''large'''] _lowercase : Optional[int] ='''lm_head.decoder.weight''' _lowercase : Optional[Any] ='''lm_head.weight''' def A__ ( lowercase: int, lowercase: Dict ) -> int: A : int =torch.load(__snake_case ) A : Optional[Any] =d.pop(__snake_case ) os.makedirs(__snake_case, exist_ok=__snake_case ) torch.save(__snake_case, os.path.join(__snake_case, __snake_case ) ) if __name__ == "__main__": _lowercase : Dict =argparse.ArgumentParser() parser.add_argument('''--dialogpt_path''', default='''.''', type=str) _lowercase : Optional[Any] =parser.parse_args() for MODEL in DIALOGPT_MODELS: _lowercase : Tuple =os.path.join(args.dialogpt_path, f'''{MODEL}_ft.pkl''') _lowercase : Any =f'''./DialoGPT-{MODEL}''' convert_dialogpt_checkpoint( checkpoint_path, pytorch_dump_folder_path, )
712
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> str: # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_checkpoint_path''', default=None, type=str, required=True, help=( '''Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,''' ''' bpecodes, etc.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
0
'''simple docstring''' import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def lowercase_ ( __A : str ) -> Union[str, Any]: """simple docstring""" return x + 2 class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def A__ ( self : Dict ) -> List[Any]: '''simple docstring''' lowercase : Optional[int] ='''x = 3''' lowercase : Any ={} lowercase : Union[str, Any] =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) assert result == 3 self.assertDictEqual(UpperCAmelCase , {'''x''': 3} ) lowercase : str ='''x = y''' lowercase : Optional[int] ={'''y''': 5} lowercase : List[str] =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase , {'''x''': 5, '''y''': 5} ) def A__ ( self : str ) -> Optional[int]: '''simple docstring''' lowercase : Optional[int] ='''y = add_two(x)''' lowercase : str ={'''x''': 3} lowercase : List[str] =evaluate(UpperCAmelCase , {'''add_two''': add_two} , state=UpperCAmelCase ) assert result == 5 self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''y''': 5} ) # Won't work without the tool with CaptureStdout() as out: lowercase : Optional[Any] =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) assert result is None assert "tried to execute add_two" in out.out def A__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' lowercase : int ='''x = 3''' lowercase : Dict ={} lowercase : List[Any] =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) assert result == 3 self.assertDictEqual(UpperCAmelCase , {'''x''': 3} ) def A__ ( self : str ) -> Tuple: '''simple docstring''' lowercase : Optional[Any] ='''test_dict = {\'x\': x, \'y\': add_two(x)}''' lowercase : str ={'''x''': 3} lowercase : Tuple =evaluate(UpperCAmelCase , {'''add_two''': add_two} , state=UpperCAmelCase ) self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''y''': 5} ) self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}} ) def A__ ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' lowercase : Optional[Any] ='''x = 3\ny = 5''' lowercase : int ={} lowercase : List[str] =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''y''': 5} ) def A__ ( self : Any ) -> Tuple: '''simple docstring''' lowercase : List[str] ='''text = f\'This is x: {x}.\'''' lowercase : Union[str, Any] ={'''x''': 3} lowercase : Tuple =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''text''': '''This is x: 3.'''} ) def A__ ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' lowercase : Tuple ='''if x <= 3:\n y = 2\nelse:\n y = 5''' lowercase : Union[str, Any] ={'''x''': 3} lowercase : Any =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''y''': 2} ) lowercase : Optional[Any] ={'''x''': 8} lowercase : str =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(UpperCAmelCase , {'''x''': 8, '''y''': 5} ) def A__ ( self : str ) -> Optional[Any]: '''simple docstring''' lowercase : List[str] ='''test_list = [x, add_two(x)]''' lowercase : Any ={'''x''': 3} lowercase : Tuple =evaluate(UpperCAmelCase , {'''add_two''': add_two} , state=UpperCAmelCase ) self.assertListEqual(UpperCAmelCase , [3, 5] ) self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''test_list''': [3, 5]} ) def A__ ( self : Any ) -> Tuple: '''simple docstring''' lowercase : str ='''y = x''' lowercase : Dict ={'''x''': 3} lowercase : Tuple =evaluate(UpperCAmelCase , {} , state=UpperCAmelCase ) assert result == 3 self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''y''': 3} ) def A__ ( self : str ) -> List[str]: '''simple docstring''' lowercase : Any ='''test_list = [x, add_two(x)]\ntest_list[1]''' lowercase : Any ={'''x''': 3} lowercase : Union[str, Any] =evaluate(UpperCAmelCase , {'''add_two''': add_two} , state=UpperCAmelCase ) assert result == 5 self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''test_list''': [3, 5]} ) lowercase : int ='''test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']''' lowercase : Union[str, Any] ={'''x''': 3} lowercase : Tuple =evaluate(UpperCAmelCase , {'''add_two''': add_two} , state=UpperCAmelCase ) assert result == 5 self.assertDictEqual(UpperCAmelCase , {'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}} ) def A__ ( self : List[str] ) -> Tuple: '''simple docstring''' lowercase : Optional[int] ='''x = 0\nfor i in range(3):\n x = i''' lowercase : List[str] ={} lowercase : Union[str, Any] =evaluate(UpperCAmelCase , {'''range''': range} , state=UpperCAmelCase ) assert result == 2 self.assertDictEqual(UpperCAmelCase , {'''x''': 2, '''i''': 2} )
94
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[Any] ='''src/transformers''' # Matches is_xxx_available() _lowercase : List[str] =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : Any =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Optional[int] =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : int =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : Tuple =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : List[Any] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : List[Any] =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[str] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Any =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : Optional[int] =re.compile(R'''^\s*else:''') def A__ ( lowercase: int ) -> Optional[Any]: if _re_test_backend.search(lowercase ) is None: return None A : List[str] =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Tuple ) -> int: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : str =f.readlines() A : List[str] =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Union[str, Any] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : Union[str, Any] =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : List[str] =_re_one_line_import_struct.search(lowercase ).groups()[0] A : Optional[int] =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : int =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : List[str] =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : Optional[int] ={'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. A : Dict =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : int =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : str =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : List[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : List[str] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : Optional[Any] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : int =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : List[str] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : int =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : List[str] =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 A : Dict ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : Optional[Any] =find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: A : str =None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 A : List[Any] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : List[str] =lines[line_index] A : Optional[Any] =_re_import.search(lowercase ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 A : Any =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Dict, lowercase: str ) -> int: def find_duplicates(lowercase: int ): return [k for k, v in collections.Counter(lowercase ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] A : Dict =[] for key in import_dict_objects.keys(): A : Optional[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : str =find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): A : Tuple ='base imports' if key == 'none' else F'{key} backend' errors.append(F'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F' {a} in _import_structure but not in TYPE_HINT.' ) return errors def A__ ( ) -> int: A : List[str] =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Optional[int] =os.path.join(lowercase, '__init__.py' ) A : str =parse_init(lowercase ) if objects is not None: A : Union[str, Any] =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Optional[int] =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> Dict: A : List[Any] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : List[Any] =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : Union[str, Any] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : int =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : str =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Dict =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> List[str]: # This is to make sure the transformers module imported is the one in the repo. A : Optional[Any] =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : List[Any] =spec.loader.load_module() A : Union[str, Any] =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : List[Any] ='\n'.join(F'- {module}' for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registered in the main init of Transformers:\n' F'{list_of_modules}\n' 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
305
0
"""simple docstring""" import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase ): snake_case = ['image_processor', 'tokenizer'] snake_case = 'AutoImageProcessor' snake_case = 'AutoTokenizer' def __init__( self : List[str] , SCREAMING_SNAKE_CASE_ : List[Any]=None , SCREAMING_SNAKE_CASE_ : List[str]=None , **SCREAMING_SNAKE_CASE_ : List[Any] ): lowerCamelCase__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __UpperCamelCase , ) lowerCamelCase__ = kwargs.pop("""feature_extractor""" ) lowerCamelCase__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__UpperCamelCase , __UpperCamelCase ) lowerCamelCase__ = self.image_processor lowerCamelCase__ = False def __call__( self : Union[str, Any] , *SCREAMING_SNAKE_CASE_ : str , **SCREAMING_SNAKE_CASE_ : Optional[Any] ): if self._in_target_context_manager: return self.current_processor(*__UpperCamelCase , **__UpperCamelCase ) lowerCamelCase__ = kwargs.pop("""images""" , __UpperCamelCase ) lowerCamelCase__ = kwargs.pop("""text""" , __UpperCamelCase ) if len(__UpperCamelCase ) > 0: lowerCamelCase__ = args[0] lowerCamelCase__ = args[1:] if images is None and text is None: raise ValueError("""You need to specify either an `images` or `text` input to process.""" ) if images is not None: lowerCamelCase__ = self.image_processor(__UpperCamelCase , *__UpperCamelCase , **__UpperCamelCase ) if text is not None: lowerCamelCase__ = self.tokenizer(__UpperCamelCase , **__UpperCamelCase ) if text is None: return inputs elif images is None: return encodings else: lowerCamelCase__ = encodings["""input_ids"""] return inputs def __UpperCAmelCase ( self : Union[str, Any] , *SCREAMING_SNAKE_CASE_ : int , **SCREAMING_SNAKE_CASE_ : Tuple ): return self.tokenizer.batch_decode(*__UpperCamelCase , **__UpperCamelCase ) def __UpperCAmelCase ( self : Tuple , *SCREAMING_SNAKE_CASE_ : int , **SCREAMING_SNAKE_CASE_ : Union[str, Any] ): return self.tokenizer.decode(*__UpperCamelCase , **__UpperCamelCase ) @contextmanager def __UpperCAmelCase ( self : Tuple ): 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 images inputs, or in a separate call.""" ) lowerCamelCase__ = True lowerCamelCase__ = self.tokenizer yield lowerCamelCase__ = self.image_processor lowerCamelCase__ = False def __UpperCAmelCase ( self : str , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Optional[Any]=False , SCREAMING_SNAKE_CASE_ : Union[str, Any]=None ): if added_vocab is None: lowerCamelCase__ = self.tokenizer.get_added_vocab() lowerCamelCase__ = {} while tokens: lowerCamelCase__ = re.search(r"""<s_(.*?)>""" , __UpperCamelCase , re.IGNORECASE ) if start_token is None: break lowerCamelCase__ = start_token.group(1 ) lowerCamelCase__ = re.search(rf"""</s_{key}>""" , __UpperCamelCase , re.IGNORECASE ) lowerCamelCase__ = start_token.group() if end_token is None: lowerCamelCase__ = tokens.replace(__UpperCamelCase , """""" ) else: lowerCamelCase__ = end_token.group() lowerCamelCase__ = re.escape(__UpperCamelCase ) lowerCamelCase__ = re.escape(__UpperCamelCase ) lowerCamelCase__ = re.search(f"""{start_token_escaped}(.*?){end_token_escaped}""" , __UpperCamelCase , re.IGNORECASE ) if content is not None: lowerCamelCase__ = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node lowerCamelCase__ = self.tokenajson(__UpperCamelCase , is_inner_value=__UpperCamelCase , added_vocab=__UpperCamelCase ) if value: if len(__UpperCamelCase ) == 1: lowerCamelCase__ = value[0] lowerCamelCase__ = value else: # leaf nodes lowerCamelCase__ = [] for leaf in content.split(r"""<sep/>""" ): lowerCamelCase__ = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": lowerCamelCase__ = leaf[1:-2] # for categorical special tokens output[key].append(__UpperCamelCase ) if len(output[key] ) == 1: lowerCamelCase__ = output[key][0] lowerCamelCase__ = tokens[tokens.find(__UpperCamelCase ) + len(__UpperCamelCase ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=__UpperCamelCase , added_vocab=__UpperCamelCase ) if len(__UpperCamelCase ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def __UpperCAmelCase ( self : Tuple ): warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __UpperCamelCase , ) return self.image_processor_class @property def __UpperCAmelCase ( self : List[str] ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , __UpperCamelCase , ) return self.image_processor
719
"""simple docstring""" from manim import * class SCREAMING_SNAKE_CASE__ ( _SCREAMING_SNAKE_CASE ): def __UpperCAmelCase ( self : int ): lowerCamelCase__ = Rectangle(height=0.5 , width=0.5 ) lowerCamelCase__ = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) lowerCamelCase__ = Rectangle(height=0.2_5 , width=0.2_5 ) lowerCamelCase__ = [mem.copy() for i in range(6 )] lowerCamelCase__ = [mem.copy() for i in range(6 )] lowerCamelCase__ = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) lowerCamelCase__ = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) lowerCamelCase__ = VGroup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) lowerCamelCase__ = Text("""CPU""" , font_size=24 ) lowerCamelCase__ = Group(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE_ ) cpu.move_to([-2.5, -0.5, 0] ) self.add(SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = [mem.copy() for i in range(4 )] lowerCamelCase__ = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) lowerCamelCase__ = Text("""GPU""" , font_size=24 ) lowerCamelCase__ = Group(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE_ ) gpu.move_to([-1, -1, 0] ) self.add(SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = [mem.copy() for i in range(6 )] lowerCamelCase__ = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) lowerCamelCase__ = Text("""Model""" , font_size=24 ) lowerCamelCase__ = Group(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE_ ) model.move_to([3, -1.0, 0] ) self.add(SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = [] lowerCamelCase__ = [] for i, rect in enumerate(SCREAMING_SNAKE_CASE_ ): lowerCamelCase__ = fill.copy().set_fill(SCREAMING_SNAKE_CASE_ , opacity=0.8 ) target.move_to(SCREAMING_SNAKE_CASE_ ) model_arr.append(SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0.0 ).set_fill(SCREAMING_SNAKE_CASE_ , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(SCREAMING_SNAKE_CASE_ ) self.add(*SCREAMING_SNAKE_CASE_ , *SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = [meta_mem.copy() for i in range(6 )] lowerCamelCase__ = [meta_mem.copy() for i in range(6 )] lowerCamelCase__ = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) lowerCamelCase__ = VGroup(*SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) lowerCamelCase__ = VGroup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0 ) lowerCamelCase__ = Text("""Disk""" , font_size=24 ) lowerCamelCase__ = Group(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ).arrange(SCREAMING_SNAKE_CASE_ , buff=0.5 , aligned_edge=SCREAMING_SNAKE_CASE_ ) disk.move_to([-4, -1.2_5, 0] ) self.add(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) lowerCamelCase__ = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=18 , ) key_text.move_to([-5, 2.4, 0] ) self.add(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=18 , ) blue_text.next_to(SCREAMING_SNAKE_CASE_ , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(SCREAMING_SNAKE_CASE_ ) lowerCamelCase__ = MarkupText( f"""Now watch as an input is passed through the model\nand how the memory is utilized and handled.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase__ = Square(0.3 ) input.set_fill(SCREAMING_SNAKE_CASE_ , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , SCREAMING_SNAKE_CASE_ , buff=0.5 ) self.play(Write(SCREAMING_SNAKE_CASE_ ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=SCREAMING_SNAKE_CASE_ , buff=0.0_2 ) self.play(MoveToTarget(SCREAMING_SNAKE_CASE_ ) ) self.play(FadeOut(SCREAMING_SNAKE_CASE_ ) ) lowerCamelCase__ = Arrow(start=SCREAMING_SNAKE_CASE_ , end=SCREAMING_SNAKE_CASE_ , color=SCREAMING_SNAKE_CASE_ , buff=0.5 ) a.next_to(model_arr[0].get_left() , SCREAMING_SNAKE_CASE_ , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) lowerCamelCase__ = MarkupText( f"""As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.""" , font_size=24 , ) step_a.move_to([2, 2, 0] ) self.play(Write(SCREAMING_SNAKE_CASE_ , run_time=3 ) ) lowerCamelCase__ = {"""run_time""": 1, """fade_in""": True, """fade_out""": True, """buff""": 0.0_2} self.play( Write(SCREAMING_SNAKE_CASE_ ) , Circumscribe(model_arr[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(model_cpu_arr[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(gpu_rect[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) lowerCamelCase__ = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.0_2 , SCREAMING_SNAKE_CASE_ , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.0_2 ) lowerCamelCase__ = AnimationGroup( FadeOut(SCREAMING_SNAKE_CASE_ , run_time=0.5 ) , MoveToTarget(SCREAMING_SNAKE_CASE_ , run_time=0.5 ) , FadeIn(SCREAMING_SNAKE_CASE_ , run_time=0.5 ) , lag_ratio=0.2 ) self.play(SCREAMING_SNAKE_CASE_ ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: lowerCamelCase__ = 0.7 self.play( Circumscribe(model_arr[i] , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(cpu_left_col_base[i] , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(cpu_left_col_base[i + 1] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(gpu_rect[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(model_arr[i + 1] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.0_2 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(cpu_left_col_base[-1] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , Circumscribe(gpu_rect[0] , color=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) lowerCamelCase__ = a_c lowerCamelCase__ = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.0_2 , buff=0.5 ) self.play( FadeOut(SCREAMING_SNAKE_CASE_ ) , FadeOut(SCREAMING_SNAKE_CASE_ , run_time=0.5 ) , ) lowerCamelCase__ = MarkupText(f"""Inference on a model too large for GPU memory\nis successfully completed.""" , font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(SCREAMING_SNAKE_CASE_ , run_time=3 ) , MoveToTarget(SCREAMING_SNAKE_CASE_ ) ) self.wait()
258
0
"""simple docstring""" import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput __A : Any = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _a ( lowerCAmelCase): """simple docstring""" def __init__( self : int , *__UpperCamelCase : str , __UpperCamelCase : Optional[Any]=None , __UpperCamelCase : Dict=None , __UpperCamelCase : Any=None , **__UpperCamelCase : Union[str, Any] )->str: super().__init__(*__UpperCamelCase , **__UpperCamelCase ) _UpperCAmelCase = eval_examples _UpperCAmelCase = post_process_function _UpperCAmelCase = quant_trainer_args _UpperCAmelCase = 1_2_8 # default number of calibration samples def lowercase__ ( self : int , __UpperCamelCase : Optional[int]=None )->Tuple: if calib_dataset is None and self.calib_dataset is None: raise ValueError('''Trainer: calibration requires an calib_dataset.''' ) _UpperCAmelCase = calib_dataset if calib_dataset is not None else self.calib_dataset _UpperCAmelCase = self._remove_unused_columns(__UpperCamelCase , description='''Calibration''' ) return DataLoader( __UpperCamelCase , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=__UpperCamelCase , ) def lowercase__ ( self : str , __UpperCamelCase : Any=None )->List[str]: _UpperCAmelCase = self.train_dataset if calib_dataset is None else calib_dataset _UpperCAmelCase = self.get_calib_dataloader(__UpperCamelCase ) _UpperCAmelCase = self.model quant_trainer.configure_model(__UpperCamelCase , self.quant_trainer_args , calib=__UpperCamelCase ) model.eval() quant_trainer.enable_calibration(__UpperCamelCase ) logger.info('''***** Running calibration *****''' ) logger.info(F' Num examples = {self.calib_num}' ) logger.info(F' Batch size = {calib_dataloader.batch_size}' ) for step, inputs in enumerate(__UpperCamelCase ): # Prediction step _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = self.prediction_step(__UpperCamelCase , __UpperCamelCase , prediction_loss_only=__UpperCamelCase ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(__UpperCamelCase , self.quant_trainer_args ) _UpperCAmelCase = model def lowercase__ ( self : Union[str, Any] , __UpperCamelCase : List[str]=None , __UpperCamelCase : List[Any]=None , __UpperCamelCase : Any=None , __UpperCamelCase : str = "eval" )->Tuple: _UpperCAmelCase = self.eval_dataset if eval_dataset is None else eval_dataset _UpperCAmelCase = self.get_eval_dataloader(__UpperCamelCase ) _UpperCAmelCase = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. _UpperCAmelCase = self.compute_metrics _UpperCAmelCase = None _UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _UpperCAmelCase = eval_loop( __UpperCamelCase , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__UpperCamelCase , ) finally: _UpperCAmelCase = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: _UpperCAmelCase = self.post_process_function(__UpperCamelCase , __UpperCamelCase , output.predictions ) _UpperCAmelCase = self.compute_metrics(__UpperCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'{metric_key_prefix}_' ): _UpperCAmelCase = metrics.pop(__UpperCamelCase ) self.log(__UpperCamelCase ) else: _UpperCAmelCase = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) _UpperCAmelCase = self.callback_handler.on_evaluate(self.args , self.state , self.control , __UpperCamelCase ) return metrics def lowercase__ ( self : int , __UpperCamelCase : List[Any] , __UpperCamelCase : Optional[int] , __UpperCamelCase : List[Any]=None , __UpperCamelCase : str = "test" )->List[str]: _UpperCAmelCase = self.get_test_dataloader(__UpperCamelCase ) # Temporarily disable metric computation, we will do it in the loop here. _UpperCAmelCase = self.compute_metrics _UpperCAmelCase = None _UpperCAmelCase = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: _UpperCAmelCase = eval_loop( __UpperCamelCase , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__UpperCamelCase , ) finally: _UpperCAmelCase = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output _UpperCAmelCase = self.post_process_function(__UpperCamelCase , __UpperCamelCase , output.predictions , '''predict''' ) _UpperCAmelCase = self.compute_metrics(__UpperCamelCase ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'{metric_key_prefix}_' ): _UpperCAmelCase = metrics.pop(__UpperCamelCase ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__UpperCamelCase ) def lowercase__ ( self : Dict , __UpperCamelCase : Optional[int]="./" )->Union[str, Any]: _UpperCAmelCase = self.eval_dataset _UpperCAmelCase = self.get_eval_dataloader(__UpperCamelCase ) _UpperCAmelCase = next(iter(__UpperCamelCase ) ) # saving device - to make it consistent _UpperCAmelCase = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) # convert to tuple _UpperCAmelCase = tuple(v.to(__UpperCamelCase ) for k, v in batch.items() ) logger.info('''Converting model to be onnx compatible''' ) from pytorch_quantization.nn import TensorQuantizer _UpperCAmelCase = True _UpperCAmelCase = self.model.to(__UpperCamelCase ) model.eval() model.float() _UpperCAmelCase = model.module if hasattr(__UpperCamelCase , '''module''' ) else model quant_trainer.configure_model(__UpperCamelCase , self.quant_trainer_args ) _UpperCAmelCase = os.path.join(__UpperCamelCase , '''model.onnx''' ) logger.info(F'exporting model to {output_model_file}' ) _UpperCAmelCase = {0: '''batch_size''', 1: '''seq_len'''} torch.onnx.export( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , export_params=__UpperCamelCase , opset_version=1_3 , do_constant_folding=__UpperCamelCase , input_names=['''input_ids''', '''attention_mask''', '''token_type_ids'''] , output_names=['''output_start_logits''', '''output_end_logits'''] , dynamic_axes={ '''input_ids''': axes, '''attention_mask''': axes, '''token_type_ids''': axes, '''output_start_logits''': axes, '''output_end_logits''': axes, } , verbose=__UpperCamelCase , ) logger.info('''onnx export finished''' )
602
"""simple docstring""" import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging __A : List[str] = logging.get_logger(__name__) def lowercase ( _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any] , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : str=False ): '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( '''Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise if not is_sharded: _UpperCAmelCase = os.path.abspath(_SCREAMING_SNAKE_CASE ) logger.info(f'Loading PyTorch weights from {pt_path}' ) _UpperCAmelCase = torch.load(_SCREAMING_SNAKE_CASE , map_location='''cpu''' ) logger.info(f'PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters.' ) _UpperCAmelCase = convert_pytorch_state_dict_to_flax(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files _UpperCAmelCase = convert_pytorch_sharded_state_dict_to_flax(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return flax_state_dict def lowercase ( _SCREAMING_SNAKE_CASE : Tuple[str] , _SCREAMING_SNAKE_CASE : np.ndarray , _SCREAMING_SNAKE_CASE : Dict[str, jnp.ndarray] , _SCREAMING_SNAKE_CASE : str , ): '''simple docstring''' def is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE : Tuple[str] ) -> bool: return len(set(_SCREAMING_SNAKE_CASE ) & {key, (model_prefix,) + key} ) > 0 # layer norm _UpperCAmelCase = pt_tuple_key[:-1] + ('''scale''',) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean _UpperCAmelCase = pt_tuple_key[:-1] + ('''mean''',) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var _UpperCAmelCase = pt_tuple_key[:-1] + ('''var''',) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # embedding _UpperCAmelCase = pt_tuple_key[:-1] + ('''embedding''',) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): return renamed_pt_tuple_key, pt_tensor # conv layer _UpperCAmelCase = pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer _UpperCAmelCase = pt_tuple_key[:-1] + ('''kernel''',) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight _UpperCAmelCase = pt_tuple_key[:-1] + ('''weight''',) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias _UpperCAmelCase = pt_tuple_key[:-1] + ('''bias''',) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 _UpperCAmelCase = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): _UpperCAmelCase = pt_tuple_key[-2] + '''_g''' elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): _UpperCAmelCase = pt_tuple_key[-2] + '''_v''' if name is not None: _UpperCAmelCase = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def lowercase ( _SCREAMING_SNAKE_CASE : List[Any] , _SCREAMING_SNAKE_CASE : List[Any] ): '''simple docstring''' _UpperCAmelCase = {k: v.numpy() for k, v in pt_state_dict.items()} _UpperCAmelCase = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: _UpperCAmelCase = flax_model.params['''params'''] else: _UpperCAmelCase = flax_model.params _UpperCAmelCase = flatten_dict(_SCREAMING_SNAKE_CASE ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: _UpperCAmelCase = flatten_dict(flax_model.params['''batch_stats'''] ) random_flax_state_dict.update(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = {} _UpperCAmelCase = (model_prefix not in flax_model_params) and ( model_prefix in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) _UpperCAmelCase = (model_prefix in flax_model_params) and ( model_prefix not in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): _UpperCAmelCase = tuple(pt_key.split('''.''' ) ) # remove base model prefix if necessary _UpperCAmelCase = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: _UpperCAmelCase = pt_tuple_key[1:] # Correctly rename weight parameters _UpperCAmelCase , _UpperCAmelCase = rename_key_and_reshape_tensor( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # add model prefix if necessary _UpperCAmelCase = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: _UpperCAmelCase = (model_prefix,) + flax_key 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}.' ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: _UpperCAmelCase = jnp.asarray(_SCREAMING_SNAKE_CASE ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue # also add unexpected weight so that warning is thrown _UpperCAmelCase = jnp.asarray(_SCREAMING_SNAKE_CASE ) else: # also add unexpected weight so that warning is thrown _UpperCAmelCase = jnp.asarray(_SCREAMING_SNAKE_CASE ) return unflatten_dict(_SCREAMING_SNAKE_CASE ) def lowercase ( _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' import torch # Load the index _UpperCAmelCase = {} for shard_file in shard_filenames: # load using msgpack utils _UpperCAmelCase = torch.load(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = {k: v.numpy() for k, v in pt_state_dict.items()} _UpperCAmelCase = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: _UpperCAmelCase = flax_model.params['''params'''] _UpperCAmelCase = flatten_dict(_SCREAMING_SNAKE_CASE ) random_flax_state_dict.update(flatten_dict(flax_model.params['''batch_stats'''] ) ) else: _UpperCAmelCase = flax_model.params _UpperCAmelCase = flatten_dict(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = (model_prefix not in flax_model_params) and ( model_prefix in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) _UpperCAmelCase = (model_prefix in flax_model_params) and ( model_prefix not in {k.split('''.''' )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): _UpperCAmelCase = tuple(pt_key.split('''.''' ) ) # remove base model prefix if necessary _UpperCAmelCase = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: _UpperCAmelCase = pt_tuple_key[1:] # Correctly rename weight parameters _UpperCAmelCase , _UpperCAmelCase = rename_key_and_reshape_tensor( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # add model prefix if necessary _UpperCAmelCase = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: _UpperCAmelCase = (model_prefix,) + flax_key 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}.' ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: _UpperCAmelCase = jnp.asarray(_SCREAMING_SNAKE_CASE ) continue if "var" in flax_key[-1]: _UpperCAmelCase = jnp.asarray(_SCREAMING_SNAKE_CASE ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) continue # also add unexpected weight so that warning is thrown _UpperCAmelCase = jnp.asarray(_SCREAMING_SNAKE_CASE ) else: # also add unexpected weight so that warning is thrown _UpperCAmelCase = jnp.asarray(_SCREAMING_SNAKE_CASE ) return unflatten_dict(_SCREAMING_SNAKE_CASE ) def lowercase ( _SCREAMING_SNAKE_CASE : Any , _SCREAMING_SNAKE_CASE : Optional[Any] ): '''simple docstring''' _UpperCAmelCase = os.path.abspath(_SCREAMING_SNAKE_CASE ) logger.info(f'Loading Flax weights from {flax_checkpoint_path}' ) # import correct flax class _UpperCAmelCase = getattr(_SCREAMING_SNAKE_CASE , '''Flax''' + model.__class__.__name__ ) # load flax weight dict with open(_SCREAMING_SNAKE_CASE , '''rb''' ) as state_f: try: _UpperCAmelCase = from_bytes(_SCREAMING_SNAKE_CASE , state_f.read() ) except UnpicklingError: raise EnvironmentError(f'Unable to convert {flax_checkpoint_path} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowercase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : int ): '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( '''Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights _UpperCAmelCase = flatten_dict(jax.tree_util.tree_map(lambda _SCREAMING_SNAKE_CASE : x.dtype == jnp.bfloataa , _SCREAMING_SNAKE_CASE ) ).values() if any(_SCREAMING_SNAKE_CASE ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) _UpperCAmelCase = jax.tree_util.tree_map( lambda _SCREAMING_SNAKE_CASE : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = flatten_dict(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pt_model.state_dict() _UpperCAmelCase = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split('''.''' )[0] for k in pt_model_dict.keys()} ) _UpperCAmelCase = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split('''.''' )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys _UpperCAmelCase = [] _UpperCAmelCase = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): _UpperCAmelCase = flax_key_tuple[0] == pt_model.base_model_prefix _UpperCAmelCase = '''.'''.join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: _UpperCAmelCase = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: _UpperCAmelCase = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(_SCREAMING_SNAKE_CASE ) not in pt_model_dict: # conv layer _UpperCAmelCase = flax_key_tuple[:-1] + ('''weight''',) _UpperCAmelCase = jnp.transpose(_SCREAMING_SNAKE_CASE , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(_SCREAMING_SNAKE_CASE ) not in pt_model_dict: # linear layer _UpperCAmelCase = flax_key_tuple[:-1] + ('''weight''',) _UpperCAmelCase = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: _UpperCAmelCase = flax_key_tuple[:-1] + ('''weight''',) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: _UpperCAmelCase = flax_key_tuple[:-1] + ('''running_mean''',) elif "var" in flax_key_tuple[-1]: _UpperCAmelCase = flax_key_tuple[:-1] + ('''running_var''',) if "batch_stats" in flax_state: _UpperCAmelCase = '''.'''.join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: _UpperCAmelCase = '''.'''.join(_SCREAMING_SNAKE_CASE ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. _UpperCAmelCase = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: _UpperCAmelCase = key.split('''.''' ) _UpperCAmelCase = None if key_components[-3::2] == ["parametrizations", "original0"]: _UpperCAmelCase = key_components[-2] + '''_g''' elif key_components[-3::2] == ["parametrizations", "original1"]: _UpperCAmelCase = key_components[-2] + '''_v''' if name is not None: _UpperCAmelCase = key_components[:-3] + [name] _UpperCAmelCase = '''.'''.join(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = key if flax_key in special_pt_names: _UpperCAmelCase = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' f'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict _UpperCAmelCase = np.asarray(_SCREAMING_SNAKE_CASE ) if not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ) else flax_tensor _UpperCAmelCase = torch.from_numpy(_SCREAMING_SNAKE_CASE ) # remove from missing keys missing_keys.remove(_SCREAMING_SNAKE_CASE ) else: # weight is not expected by PyTorch model unexpected_keys.append(_SCREAMING_SNAKE_CASE ) pt_model.load_state_dict(_SCREAMING_SNAKE_CASE ) # re-transform missing_keys to list _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) if len(_SCREAMING_SNAKE_CASE ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' f' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' f' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' f' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) else: logger.warning(f'All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n' ) if len(_SCREAMING_SNAKE_CASE ) > 0: logger.warning( f'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' f' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) else: logger.warning( f'All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n' '''If your task is similar to the task the model of the checkpoint was trained on, ''' f'you can already use {pt_model.__class__.__name__} for predictions without further training.' ) return pt_model
602
1
from . import __version__ # Backward compatibility imports, to make sure all those objects can be found in file_utils from .utils import ( CLOUDFRONT_DISTRIB_PREFIX, CONFIG_NAME, DISABLE_TELEMETRY, DUMMY_INPUTS, DUMMY_MASK, ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, FEATURE_EXTRACTOR_NAME, FLAX_WEIGHTS_NAME, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, MODEL_CARD_NAME, MULTIPLE_CHOICE_DUMMY_INPUTS, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, SENTENCEPIECE_UNDERLINE, SPIECE_UNDERLINE, TF2_WEIGHTS_NAME, TF_WEIGHTS_NAME, TORCH_FX_REQUIRED_VERSION, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, USE_JAX, USE_TF, USE_TORCH, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ContextManagers, DummyObject, EntryNotFoundError, ExplicitEnum, ModelOutput, PaddingStrategy, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, TensorType, _LazyModule, add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, cached_property, copy_func, default_cache_path, define_sagemaker_information, get_cached_models, get_file_from_repo, get_full_repo_name, get_torch_version, has_file, http_user_agent, is_apex_available, is_bsa_available, is_coloredlogs_available, is_datasets_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_librosa_available, is_offline_mode, is_onnx_available, is_pandas_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytorch_quantization_available, is_rjieba_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_tensor, is_tensorflow_probability_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_training_run_on_sagemaker, is_vision_available, replace_return_docstrings, requires_backends, to_numpy, to_py_obj, torch_only_method, )
720
import math import time from typing import Dict, List, Optional from torch.utils.data import Dataset from transformers import SeqaSeqTrainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput, speed_metrics if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class __a ( __A ): '''simple docstring''' def __init__( self , *UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__=None , **UpperCamelCase__ ): super().__init__(*UpperCamelCase__ , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ : Dict = eval_examples SCREAMING_SNAKE_CASE_ : int = post_process_function def __snake_case ( self , UpperCamelCase__ = None , UpperCamelCase__=None , UpperCamelCase__ = None , UpperCamelCase__ = "eval" , **UpperCamelCase__ , ): SCREAMING_SNAKE_CASE_ : int = gen_kwargs.copy() SCREAMING_SNAKE_CASE_ : Tuple = ( gen_kwargs['max_length'] if gen_kwargs.get('max_length' ) is not None else self.args.generation_max_length ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( gen_kwargs['num_beams'] if gen_kwargs.get('num_beams' ) is not None else self.args.generation_num_beams ) SCREAMING_SNAKE_CASE_ : Optional[Any] = gen_kwargs SCREAMING_SNAKE_CASE_ : Tuple = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE_ : int = self.get_eval_dataloader(UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ : Any = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.compute_metrics SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : Union[str, Any] = time.time() SCREAMING_SNAKE_CASE_ : int = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE_ : List[Any] = eval_loop( UpperCamelCase__ , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase__ , metric_key_prefix=UpperCamelCase__ , ) finally: SCREAMING_SNAKE_CASE_ : Optional[int] = compute_metrics SCREAMING_SNAKE_CASE_ : Dict = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( UpperCamelCase__ , UpperCamelCase__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save: # Only the main node write the results by default SCREAMING_SNAKE_CASE_ : List[str] = self.post_process_function(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.compute_metrics(UpperCamelCase__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = metrics.pop(UpperCamelCase__ ) metrics.update(output.metrics ) else: SCREAMING_SNAKE_CASE_ : Tuple = output.metrics if self.args.should_log: # Only the main node log the results by default self.log(UpperCamelCase__ ) if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE_ : Dict = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCamelCase__ ) return metrics def __snake_case ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=None , UpperCamelCase__ = "test" , **UpperCamelCase__ ): SCREAMING_SNAKE_CASE_ : List[Any] = gen_kwargs.copy() SCREAMING_SNAKE_CASE_ : Any = self.get_test_dataloader(UpperCamelCase__ ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE_ : Tuple = self.compute_metrics SCREAMING_SNAKE_CASE_ : str = None SCREAMING_SNAKE_CASE_ : Optional[Any] = time.time() SCREAMING_SNAKE_CASE_ : List[Any] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE_ : List[str] = eval_loop( UpperCamelCase__ , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCamelCase__ , metric_key_prefix=UpperCamelCase__ , ) finally: SCREAMING_SNAKE_CASE_ : Union[str, Any] = compute_metrics SCREAMING_SNAKE_CASE_ : List[str] = self.args.eval_batch_size * self.args.world_size if F'''{metric_key_prefix}_jit_compilation_time''' in output.metrics: start_time += output.metrics[F'''{metric_key_prefix}_jit_compilation_time'''] output.metrics.update( speed_metrics( UpperCamelCase__ , UpperCamelCase__ , num_samples=output.num_samples , num_steps=math.ceil(output.num_samples / total_batch_size ) , ) ) if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE_ : Optional[int] = self.post_process_function(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , 'predict' ) SCREAMING_SNAKE_CASE_ : List[Any] = self.compute_metrics(UpperCamelCase__ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE_ : Optional[int] = metrics.pop(UpperCamelCase__ ) metrics.update(output.metrics ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCamelCase__ )
97
0