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''' import glob import os import random from string import ascii_lowercase, digits import cva A_ = "" A_ = "" A_ = "" A_ = 1 # (0 is vertical, 1 is horizontal) def _UpperCamelCase ( ) -> None: lowerCamelCase_ ,lowerCamelCase_ = get_dataset(__UpperCamelCase ,__UpperCamelCase ) print('Processing...' ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = update_image_and_anno(__UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase ) for index, image in enumerate(__UpperCamelCase ): # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' lowerCamelCase_ = random_chars(32 ) lowerCamelCase_ = paths[index].split(os.sep )[-1].rsplit('.' ,1 )[0] lowerCamelCase_ = f'''{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}''' cva.imwrite(f'''/{file_root}.jpg''' ,__UpperCamelCase ,[cva.IMWRITE_JPEG_QUALITY, 85] ) print(f'''Success {index+1}/{len(__UpperCamelCase )} with {file_name}''' ) lowerCamelCase_ = [] for anno in new_annos[index]: lowerCamelCase_ = f'''{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}''' annos_list.append(__UpperCamelCase ) with open(f'''/{file_root}.txt''' ,'w' ) as outfile: outfile.write('\n'.join(line for line in annos_list ) ) def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ) -> tuple[list, list]: lowerCamelCase_ = [] lowerCamelCase_ = [] for label_file in glob.glob(os.path.join(__UpperCamelCase ,'*.txt' ) ): lowerCamelCase_ = label_file.split(os.sep )[-1].rsplit('.' ,1 )[0] with open(__UpperCamelCase ) as in_file: lowerCamelCase_ = in_file.readlines() lowerCamelCase_ = os.path.join(__UpperCamelCase ,f'''{label_name}.jpg''' ) lowerCamelCase_ = [] for obj_list in obj_lists: lowerCamelCase_ = obj_list.rstrip('\n' ).split(' ' ) boxes.append( [ int(obj[0] ), float(obj[1] ), float(obj[2] ), float(obj[3] ), float(obj[4] ), ] ) if not boxes: continue img_paths.append(__UpperCamelCase ) labels.append(__UpperCamelCase ) return img_paths, labels def _UpperCamelCase ( __UpperCamelCase ,__UpperCamelCase ,__UpperCamelCase = 1 ) -> tuple[list, list, list]: lowerCamelCase_ = [] lowerCamelCase_ = [] lowerCamelCase_ = [] for idx in range(len(__UpperCamelCase ) ): lowerCamelCase_ = [] lowerCamelCase_ = img_list[idx] path_list.append(__UpperCamelCase ) lowerCamelCase_ = anno_list[idx] lowerCamelCase_ = cva.imread(__UpperCamelCase ) if flip_type == 1: lowerCamelCase_ = cva.flip(__UpperCamelCase ,__UpperCamelCase ) for bbox in img_annos: lowerCamelCase_ = 1 - bbox[1] new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] ) elif flip_type == 0: lowerCamelCase_ = cva.flip(__UpperCamelCase ,__UpperCamelCase ) for bbox in img_annos: lowerCamelCase_ = 1 - bbox[2] new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] ) new_annos_lists.append(__UpperCamelCase ) new_imgs_list.append(__UpperCamelCase ) return new_imgs_list, new_annos_lists, path_list def _UpperCamelCase ( __UpperCamelCase = 32 ) -> str: assert number_char > 1, "The number of character should greater than 1" lowerCamelCase_ = ascii_lowercase + digits return "".join(random.choice(__UpperCamelCase ) for _ in range(__UpperCamelCase ) ) if __name__ == "__main__": main() print("DONE ✅")
42
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class __UpperCamelCase ( unittest.TestCase ): @slow def __UpperCAmelCase ( self ): '''simple docstring''' __a : int = TFCamembertModel.from_pretrained('jplu/tf-camembert-base' ) __a : str = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" __a : Optional[int] = model(__a )['last_hidden_state'] __a : Optional[int] = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , __a ) # compare the actual values for a slice. __a : List[str] = tf.convert_to_tensor( [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
476
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available A_ : Union[str, Any] = { "configuration_audio_spectrogram_transformer": [ "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "ASTConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Tuple = [ "AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "ASTForAudioClassification", "ASTModel", "ASTPreTrainedModel", ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : Dict = ["ASTFeatureExtractor"] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys A_ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
696
"""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_ : 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.01), "suppress_tokens": [0, 1], "begin_suppress_tokens": 2, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } @is_staging_test class a_ ( unittest.TestCase ): '''simple docstring''' @classmethod def a__ (cls ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = TOKEN HfFolder.save_token(lowerCamelCase_ ) @classmethod def a__ (cls ): '''simple docstring''' 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 a__ (self ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = BertConfig( vocab_size=9_9, hidden_size=3_2, num_hidden_layers=5, num_attention_heads=4, intermediate_size=3_7 ) config.push_to_hub('test-config', use_auth_token=self._token ) lowerCamelCase__ : Optional[int] = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_, getattr(lowerCamelCase_, lowerCamelCase_ ) ) # 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(lowerCamelCase_, repo_id='test-config', push_to_hub=lowerCamelCase_, use_auth_token=self._token ) lowerCamelCase__ : List[str] = BertConfig.from_pretrained(f'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_, getattr(lowerCamelCase_, lowerCamelCase_ ) ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : str = BertConfig( vocab_size=9_9, hidden_size=3_2, num_hidden_layers=5, num_attention_heads=4, intermediate_size=3_7 ) config.push_to_hub('valid_org/test-config-org', use_auth_token=self._token ) lowerCamelCase__ : Union[str, Any] = BertConfig.from_pretrained('valid_org/test-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_, getattr(lowerCamelCase_, lowerCamelCase_ ) ) # 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( lowerCamelCase_, repo_id='valid_org/test-config-org', push_to_hub=lowerCamelCase_, use_auth_token=self._token ) lowerCamelCase__ : str = BertConfig.from_pretrained('valid_org/test-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase_, getattr(lowerCamelCase_, lowerCamelCase_ ) ) def a__ (self ): '''simple docstring''' CustomConfig.register_for_auto_class() lowerCamelCase__ : Optional[int] = CustomConfig(attribute=4_2 ) config.push_to_hub('test-dynamic-config', use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map, {'AutoConfig': 'custom_configuration.CustomConfig'} ) lowerCamelCase__ : List[str] = AutoConfig.from_pretrained(f'''{USER}/test-dynamic-config''', trust_remote_code=lowerCamelCase_ ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__, 'CustomConfig' ) self.assertEqual(new_config.attribute, 4_2 ) class a_ ( unittest.TestCase ): '''simple docstring''' def a__ (self ): '''simple docstring''' lowerCamelCase__ : str = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated lowerCamelCase__ : Tuple = c.n_embd + 1 # int lowerCamelCase__ : Union[str, Any] = c.resid_pdrop + 1.0 # float lowerCamelCase__ : List[Any] = not c.scale_attn_weights # bool lowerCamelCase__ : List[Any] = 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(lowerCamelCase_, c.n_embd, 'mismatch for key: n_embd' ) self.assertEqual(lowerCamelCase_, c.resid_pdrop, 'mismatch for key: resid_pdrop' ) self.assertEqual(lowerCamelCase_, c.scale_attn_weights, 'mismatch for key: scale_attn_weights' ) self.assertEqual(lowerCamelCase_, c.summary_type, 'mismatch for key: summary_type' ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : List[str] = PretrainedConfig() lowerCamelCase__ : Optional[Any] = [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( lowerCamelCase_, ['is_encoder_decoder', '_name_or_path', '_commit_hash', 'transformers_version'] ) lowerCamelCase__ : Any = [key for key, value in config_common_kwargs.items() if value == getattr(lowerCamelCase_, lowerCamelCase_ )] if len(lowerCamelCase_ ) > 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(lowerCamelCase_ )}.''' ) def a__ (self ): '''simple docstring''' with self.assertRaises(lowerCamelCase_ ): # config is in subfolder, the following should not work without specifying the subfolder lowerCamelCase__ : Union[str, Any] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder' ) lowerCamelCase__ : int = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder', subfolder='bert' ) self.assertIsNotNone(lowerCamelCase_ ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : str = mock.Mock() lowerCamelCase__ : List[str] = 5_0_0 lowerCamelCase__ : Any = {} lowerCamelCase__ : int = HTTPError lowerCamelCase__ : Optional[Any] = {} # Download this model to make sure it's in the cache. lowerCamelCase__ : Any = 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=lowerCamelCase_ ) as mock_head: lowerCamelCase__ : List[str] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() def a__ (self ): '''simple docstring''' lowerCamelCase__ : Dict = BertConfig.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json' ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : Tuple = AutoConfig.from_pretrained('bert-base-cased' ) lowerCamelCase__ : str = ['config.4.0.0.json'] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(lowerCamelCase_ ) lowerCamelCase__ : Optional[Any] = 2 json.dump(configuration.to_dict(), open(os.path.join(lowerCamelCase_, 'config.4.0.0.json' ), 'w' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 lowerCamelCase__ : Union[str, Any] = AutoConfig.from_pretrained(lowerCamelCase_ ) 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__ : str = ['config.42.0.0.json'] lowerCamelCase__ : Union[str, Any] = 7_6_8 configuration.save_pretrained(lowerCamelCase_ ) shutil.move(os.path.join(lowerCamelCase_, 'config.4.0.0.json' ), os.path.join(lowerCamelCase_, 'config.42.0.0.json' ) ) lowerCamelCase__ : Union[str, Any] = AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertEqual(new_configuration.hidden_size, 7_6_8 ) def a__ (self ): '''simple docstring''' lowerCamelCase__ : Optional[int] = 'hf-internal-testing/test-two-configs' import transformers as new_transformers lowerCamelCase__ : Optional[int] = 'v4.0.0' lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = new_transformers.models.auto.AutoConfig.from_pretrained( lowerCamelCase_, return_unused_kwargs=lowerCamelCase_ ) self.assertEqual(new_configuration.hidden_size, 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(lowerCamelCase_, {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers lowerCamelCase__ : Dict = 'v3.0.0' lowerCamelCase__ : List[str] = old_transformers.models.auto.AutoConfig.from_pretrained(lowerCamelCase_ ) self.assertEqual(old_configuration.hidden_size, 7_6_8 )
696
1
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, 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.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self ,lowerCamelCase_ ,lowerCamelCase_=1_3 ,lowerCamelCase_=7 ,lowerCamelCase_=True ,lowerCamelCase_=True ,lowerCamelCase_=True ,lowerCamelCase_=True ,lowerCamelCase_=9_9 ,lowerCamelCase_=3_2 ,lowerCamelCase_=5 ,lowerCamelCase_=4 ,lowerCamelCase_=3_7 ,lowerCamelCase_="gelu" ,lowerCamelCase_=0.1 ,lowerCamelCase_=0.1 ,lowerCamelCase_=5_1_2 ,lowerCamelCase_=1_6 ,lowerCamelCase_=2 ,lowerCamelCase_=0.02 ,lowerCamelCase_=4 ,) -> Dict: A = parent A = batch_size A = seq_length A = is_training A = use_attention_mask A = use_token_type_ids A = use_labels A = vocab_size A = hidden_size A = num_hidden_layers A = num_attention_heads A = intermediate_size A = hidden_act A = hidden_dropout_prob A = attention_probs_dropout_prob A = max_position_embeddings A = type_vocab_size A = type_sequence_label_size A = initializer_range A = num_choices def UpperCamelCase__ ( self ) -> int: A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) A = None if self.use_attention_mask: A = random_attention_mask([self.batch_size, self.seq_length] ) A = None if self.use_token_type_ids: A = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) A = RoFormerConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=lowerCamelCase_ ,initializer_range=self.initializer_range ,) return config, input_ids, token_type_ids, attention_mask def UpperCamelCase__ ( self ) -> Optional[Any]: A = self.prepare_config_and_inputs() A , A , A , A = config_and_inputs A = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_flax class lowerCamelCase__ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' _lowerCamelCase = True _lowerCamelCase = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase__ ( self ) -> int: A = FlaxRoFormerModelTester(self ) @slow def UpperCamelCase__ ( self ) -> Optional[int]: for model_class_name in self.all_model_classes: A = model_class_name.from_pretrained("""junnyu/roformer_chinese_small""" ,from_pt=lowerCamelCase_ ) A = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase_ ) @require_flax class lowerCamelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase__ ( self ) -> Dict: A = FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) A = jnp.array([[0, 1, 2, 3, 4, 5]] ) A = model(lowerCamelCase_ )[0] A = 5_0_0_0_0 A = (1, 6, vocab_size) self.assertEqual(output.shape ,lowerCamelCase_ ) A = jnp.array( [[[-0.12_05, -1.02_65, 0.29_22], [-1.51_34, 0.19_74, 0.15_19], [-5.01_35, -3.90_03, -0.84_04]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] ,lowerCamelCase_ ,atol=1E-4 ) )
617
"""simple docstring""" from statistics import mean, stdev def _A ( _a : list , _a : int = 3 ): """simple docstring""" A = min(_a ) A = max(_a ) # normalize data return [round((x - x_min) / (x_max - x_min) , _a ) for x in data] def _A ( _a : list , _a : int = 3 ): """simple docstring""" A = mean(_a ) A = stdev(_a ) # standardize data return [round((x - mu) / (sigma) , _a ) for x in data]
617
1
"""simple docstring""" from __future__ import annotations from fractions import Fraction def __UpperCAmelCase ( _snake_case : int, _snake_case : int ): return ( num != den and num % 1_0 == den // 1_0 and (num // 1_0) / (den % 1_0) == num / den ) def __UpperCAmelCase ( _snake_case : int ): _lowercase = [] _lowercase = 1_1 _lowercase = int("1" + "0" * digit_len ) for num in range(_snake_case, _snake_case ): while den <= 9_9: if (num != den) and (num % 1_0 == den // 1_0) and (den % 1_0 != 0): if is_digit_cancelling(_snake_case, _snake_case ): solutions.append(f"""{num}/{den}""" ) den += 1 num += 1 _lowercase = 1_0 return solutions def __UpperCAmelCase ( _snake_case : int = 2 ): _lowercase = 1.0 for fraction in fraction_list(_snake_case ): _lowercase = Fraction(_snake_case ) result *= frac.denominator / frac.numerator return int(_snake_case ) if __name__ == "__main__": print(solution())
227
"""simple docstring""" import argparse import datetime def __UpperCAmelCase ( _snake_case : str ): _lowercase = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } _lowercase = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(_snake_case ) < 1_1: raise ValueError("Must be 10 characters long" ) # Get month _lowercase = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 1_3: raise ValueError("Month must be between 1 - 12" ) _lowercase = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'" ) # Get day _lowercase = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 3_2: raise ValueError("Date must be between 1 - 31" ) # Get second separator _lowercase = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'" ) # Get year _lowercase = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 4_5 < y < 8_5_0_0: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation _lowercase = datetime.date(int(_snake_case ), int(_snake_case ), int(_snake_case ) ) # Start math if m <= 2: _lowercase = y - 1 _lowercase = m + 1_2 # maths var _lowercase = int(str(_snake_case )[:2] ) _lowercase = int(str(_snake_case )[2:] ) _lowercase = int(2.6 * m - 5.3_9 ) _lowercase = int(c / 4 ) _lowercase = int(k / 4 ) _lowercase = int(d + k ) _lowercase = int(t + u + v + x ) _lowercase = int(z - (2 * c) ) _lowercase = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer." ) # Response _lowercase = f"""Your date {date_input}, is a {days[str(_snake_case )]}!""" return response if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase : Any = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) __UpperCamelCase : str = parser.parse_args() zeller(args.date_input)
227
1
"""simple docstring""" from __future__ import annotations def __A ( a_ :list[int] , a_ :int) -> list[int]: __a : int = 0 __a : Union[str, Any] = len(a_) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: __a : Optional[Any] = i + 1 else: __a : Optional[int] = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(F'{two_pointer([2, 7, 11, 15], 9) = }')
52
'''simple docstring''' from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging UpperCamelCase__ = logging.get_logger(__name__) class lowerCamelCase_ ( __a ): lowerCAmelCase__ = ['pixel_values'] def __init__( self : List[str] , _A : bool = True , _A : Dict[str, int] = None , _A : PILImageResampling = PILImageResampling.BICUBIC , _A : bool = True , _A : Dict[str, int] = None , _A : bool = True , _A : Union[int, float] = 1 / 255 , _A : bool = True , _A : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN , _A : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD , **_A : int , ): '''simple docstring''' super().__init__(**_A ) UpperCAmelCase__ : Dict = size if size is not None else {'''shortest_edge''': 224} UpperCAmelCase__ : int = get_size_dict(_A , default_to_square=_A ) UpperCAmelCase__ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCAmelCase__ : List[str] = get_size_dict(_A , param_name='''crop_size''' ) UpperCAmelCase__ : str = do_resize UpperCAmelCase__ : List[Any] = size UpperCAmelCase__ : int = resample UpperCAmelCase__ : int = do_center_crop UpperCAmelCase__ : List[str] = crop_size UpperCAmelCase__ : Union[str, Any] = do_rescale UpperCAmelCase__ : Optional[int] = rescale_factor UpperCAmelCase__ : List[Any] = do_normalize UpperCAmelCase__ : Dict = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN UpperCAmelCase__ : Dict = image_std if image_std is not None else IMAGENET_DEFAULT_STD def lowercase_ ( self : str , _A : np.ndarray , _A : Dict[str, int] , _A : PILImageResampling = PILImageResampling.BICUBIC , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Any , ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = get_size_dict(_A , default_to_square=_A ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: UpperCAmelCase__ : Tuple = int((256 / 224) * size['''shortest_edge'''] ) UpperCAmelCase__ : Tuple = get_resize_output_image_size(_A , size=_A , default_to_square=_A ) UpperCAmelCase__ : Dict = {'''height''': output_size[0], '''width''': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f"""Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}""" ) return resize( _A , size=(size_dict['''height'''], size_dict['''width''']) , resample=_A , data_format=_A , **_A ) def lowercase_ ( self : Optional[Any] , _A : np.ndarray , _A : Dict[str, int] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Optional[int] , ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = get_size_dict(_A ) if "height" not in size or "width" not in size: raise ValueError(f"""Size dict must have keys 'height' and 'width'. Got {size.keys()}""" ) return center_crop(_A , size=(size['''height'''], size['''width''']) , data_format=_A , **_A ) def lowercase_ ( self : List[str] , _A : np.ndarray , _A : Union[int, float] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Dict , ): '''simple docstring''' return rescale(_A , scale=_A , data_format=_A , **_A ) def lowercase_ ( self : Dict , _A : np.ndarray , _A : Union[float, List[float]] , _A : Union[float, List[float]] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Optional[int] , ): '''simple docstring''' return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def lowercase_ ( self : Optional[Any] , _A : ImageInput , _A : Optional[bool] = None , _A : Optional[Dict[str, int]] = None , _A : PILImageResampling = None , _A : Optional[bool] = None , _A : Optional[Dict[str, int]] = None , _A : Optional[bool] = None , _A : Optional[float] = None , _A : Optional[bool] = None , _A : Optional[Union[float, Iterable[float]]] = None , _A : Optional[Union[float, Iterable[float]]] = None , _A : Optional[TensorType] = None , _A : ChannelDimension = ChannelDimension.FIRST , **_A : str , ): '''simple docstring''' UpperCAmelCase__ : str = do_resize if do_resize is not None else self.do_resize UpperCAmelCase__ : Optional[int] = resample if resample is not None else self.resample UpperCAmelCase__ : List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase__ : Tuple = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase__ : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase__ : List[str] = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase__ : Tuple = image_mean if image_mean is not None else self.image_mean UpperCAmelCase__ : List[str] = image_std if image_std is not None else self.image_std UpperCAmelCase__ : Tuple = size if size is not None else self.size UpperCAmelCase__ : int = get_size_dict(_A , default_to_square=_A ) UpperCAmelCase__ : Union[str, Any] = crop_size if crop_size is not None else self.crop_size UpperCAmelCase__ : int = get_size_dict(_A , param_name='''crop_size''' ) UpperCAmelCase__ : Union[str, Any] = make_list_of_images(_A ) if not valid_images(_A ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. UpperCAmelCase__ : int = [to_numpy_array(_A ) for image in images] if do_resize: UpperCAmelCase__ : str = [self.resize(_A , _A , _A ) for image in images] if do_center_crop: UpperCAmelCase__ : Tuple = [self.center_crop(_A , _A ) for image in images] if do_rescale: UpperCAmelCase__ : Optional[int] = [self.rescale(_A , _A ) for image in images] if do_normalize: UpperCAmelCase__ : Any = [self.normalize(_A , _A , _A ) for image in images] UpperCAmelCase__ : Tuple = [to_channel_dimension_format(_A , _A ) for image in images] UpperCAmelCase__ : Dict = {'''pixel_values''': images} return BatchFeature(data=_A , tensor_type=_A )
75
0
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class lowerCamelCase_ ( unittest.TestCase , UpperCAmelCase_ ): '''simple docstring''' def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :Any = load_tool('''text-classification''') self.tool.setup() __UpperCamelCase :Tuple = load_tool('''text-classification''' , remote=__lowercase) def UpperCamelCase__ ( self) -> List[Any]: __UpperCamelCase :Dict = self.tool('''That\'s quite cool''' , ['''positive''', '''negative''']) self.assertEqual(__lowercase , '''positive''') def UpperCamelCase__ ( self) -> Tuple: __UpperCamelCase :List[Any] = self.remote_tool('''That\'s quite cool''' , ['''positive''', '''negative''']) self.assertEqual(__lowercase , '''positive''') def UpperCamelCase__ ( self) -> int: __UpperCamelCase :Optional[int] = self.tool(text='''That\'s quite cool''' , labels=['''positive''', '''negative''']) self.assertEqual(__lowercase , '''positive''') def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :Optional[Any] = self.remote_tool(text='''That\'s quite cool''' , labels=['''positive''', '''negative''']) self.assertEqual(__lowercase , '''positive''')
452
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase = logging.get_logger(__name__) __lowercase = { '''microsoft/wavlm-base''': '''https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json''', # See all WavLM models at https://huggingface.co/models?filter=wavlm } class lowerCamelCase_ ( UpperCAmelCase_ ): '''simple docstring''' a__ : List[Any] = """wavlm""" def __init__( self , __lowercase=32 , __lowercase=768 , __lowercase=12 , __lowercase=12 , __lowercase=3_072 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.0 , __lowercase=0.1 , __lowercase=0.1 , __lowercase=0.02 , __lowercase=1E-5 , __lowercase="group" , __lowercase="gelu" , __lowercase=(512, 512, 512, 512, 512, 512, 512) , __lowercase=(5, 2, 2, 2, 2, 2, 2) , __lowercase=(10, 3, 3, 3, 3, 2, 2) , __lowercase=False , __lowercase=128 , __lowercase=16 , __lowercase=320 , __lowercase=800 , __lowercase=False , __lowercase=True , __lowercase=0.05 , __lowercase=10 , __lowercase=2 , __lowercase=0.0 , __lowercase=10 , __lowercase=320 , __lowercase=2 , __lowercase=0.1 , __lowercase=100 , __lowercase=256 , __lowercase=256 , __lowercase=0.1 , __lowercase="mean" , __lowercase=False , __lowercase=False , __lowercase=256 , __lowercase=(512, 512, 512, 512, 1_500) , __lowercase=(5, 3, 3, 1, 1) , __lowercase=(1, 2, 3, 1, 1) , __lowercase=512 , __lowercase=80 , __lowercase=0 , __lowercase=1 , __lowercase=2 , __lowercase=False , __lowercase=3 , __lowercase=2 , __lowercase=3 , __lowercase=None , **__lowercase , ) -> Dict: super().__init__(**__lowercase , pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase) __UpperCamelCase :Any = hidden_size __UpperCamelCase :Tuple = feat_extract_norm __UpperCamelCase :List[str] = feat_extract_activation __UpperCamelCase :int = list(__lowercase) __UpperCamelCase :List[Any] = list(__lowercase) __UpperCamelCase :Union[str, Any] = list(__lowercase) __UpperCamelCase :Optional[Any] = conv_bias __UpperCamelCase :Tuple = num_buckets __UpperCamelCase :Optional[int] = max_bucket_distance __UpperCamelCase :Union[str, Any] = num_conv_pos_embeddings __UpperCamelCase :Optional[Any] = num_conv_pos_embedding_groups __UpperCamelCase :List[Any] = len(self.conv_dim) __UpperCamelCase :Tuple = num_hidden_layers __UpperCamelCase :str = intermediate_size __UpperCamelCase :Union[str, Any] = hidden_act __UpperCamelCase :Optional[int] = num_attention_heads __UpperCamelCase :str = hidden_dropout __UpperCamelCase :int = attention_dropout __UpperCamelCase :Optional[int] = activation_dropout __UpperCamelCase :str = feat_proj_dropout __UpperCamelCase :List[Any] = final_dropout __UpperCamelCase :int = layerdrop __UpperCamelCase :List[Any] = layer_norm_eps __UpperCamelCase :Optional[int] = initializer_range __UpperCamelCase :Any = num_ctc_classes __UpperCamelCase :Optional[int] = vocab_size __UpperCamelCase :List[Any] = do_stable_layer_norm __UpperCamelCase :str = use_weighted_layer_sum __UpperCamelCase :Any = classifier_proj_size if ( (len(self.conv_stride) != self.num_feat_extract_layers) or (len(self.conv_kernel) != self.num_feat_extract_layers) or (len(self.conv_dim) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f""" {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,""" f""" `len(config.conv_kernel) = {len(self.conv_kernel)}`.""") # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __UpperCamelCase :Union[str, Any] = apply_spec_augment __UpperCamelCase :Optional[Any] = mask_time_prob __UpperCamelCase :Union[str, Any] = mask_time_length __UpperCamelCase :Optional[int] = mask_time_min_masks __UpperCamelCase :str = mask_feature_prob __UpperCamelCase :Tuple = mask_feature_length # parameters for pretraining with codevector quantized representations __UpperCamelCase :Optional[Any] = num_codevectors_per_group __UpperCamelCase :List[Any] = num_codevector_groups __UpperCamelCase :str = contrastive_logits_temperature __UpperCamelCase :Tuple = num_negatives __UpperCamelCase :Any = codevector_dim __UpperCamelCase :Union[str, Any] = proj_codevector_dim __UpperCamelCase :Tuple = diversity_loss_weight # ctc loss __UpperCamelCase :int = ctc_loss_reduction __UpperCamelCase :Any = ctc_zero_infinity # adapter __UpperCamelCase :List[Any] = add_adapter __UpperCamelCase :Dict = adapter_kernel_size __UpperCamelCase :Any = adapter_stride __UpperCamelCase :Optional[int] = num_adapter_layers __UpperCamelCase :Union[str, Any] = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. __UpperCamelCase :int = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. __UpperCamelCase :Optional[Any] = list(__lowercase) __UpperCamelCase :Optional[Any] = list(__lowercase) __UpperCamelCase :List[str] = list(__lowercase) __UpperCamelCase :List[Any] = xvector_output_dim @property def UpperCamelCase__ ( self) -> Any: return functools.reduce(operator.mul , self.conv_stride , 1)
452
1
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. UpperCAmelCase__ = abspath(join(dirname(__file__), "src")) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action="ignore", category=FutureWarning) def _a ( a :Tuple ) -> Union[str, Any]: config.addinivalue_line( '''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' ) config.addinivalue_line( '''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' ) config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' ) config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' ) config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' ) config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' ) def _a ( a :Tuple ) -> List[Any]: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(_a ) def _a ( a :Union[str, Any] ) -> Optional[Any]: from transformers.testing_utils import pytest_terminal_summary_main a = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(_a , id=_a ) def _a ( a :Tuple , a :Union[str, Any] ) -> Any: if exitstatus == 5: a = 0 # Doctest custom flag to ignore output. UpperCAmelCase__ = doctest.register_optionflag("IGNORE_RESULT") UpperCAmelCase__ = doctest.OutputChecker class lowercase_ ( lowercase__ ): '''simple docstring''' def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Optional[int] , __UpperCAmelCase : Tuple , __UpperCAmelCase : List[str] ) ->Any: """simple docstring""" if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) UpperCAmelCase__ = CustomOutputChecker UpperCAmelCase__ = HfDoctestModule UpperCAmelCase__ = HfDocTestParser
117
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE : List[Any] = { "configuration_longformer": [ "LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "LongformerConfig", "LongformerOnnxConfig", ], "tokenization_longformer": ["LongformerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE : Optional[int] = ["LongformerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE : Dict = [ "LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "LongformerForMaskedLM", "LongformerForMultipleChoice", "LongformerForQuestionAnswering", "LongformerForSequenceClassification", "LongformerForTokenClassification", "LongformerModel", "LongformerPreTrainedModel", "LongformerSelfAttention", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE : Dict = [ "TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFLongformerForMaskedLM", "TFLongformerForMultipleChoice", "TFLongformerForQuestionAnswering", "TFLongformerForSequenceClassification", "TFLongformerForTokenClassification", "TFLongformerModel", "TFLongformerPreTrainedModel", "TFLongformerSelfAttention", ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys SCREAMING_SNAKE_CASE : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
257
0
'''simple docstring''' from math import factorial def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ = 100 ) -> int: return sum(int(_lowerCAmelCase ) for x in str(factorial(_lowerCAmelCase ) ) ) if __name__ == "__main__": print(solution(int(input("""Enter the Number: """).strip())))
716
import os from collections import deque import torch from torch.utils.data import Dataset class A__ ( __magic_name__ ): def __init__( self : Union[str, Any] , a : str="" , a : str="train" ): '''simple docstring''' assert os.path.isdir(a ) lowerCAmelCase__ : Optional[Any] = [] lowerCAmelCase__ : Dict = os.listdir(a ) for story_filename in story_filenames_list: if "summary" in story_filename: continue lowerCAmelCase__ : Union[str, Any] = os.path.join(a , a ) if not os.path.isfile(a ): continue self.documents.append(a ) def __len__( self : Any ): '''simple docstring''' return len(self.documents ) def __getitem__( self : Dict , a : Any ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = self.documents[idx] lowerCAmelCase__ : Union[str, Any] = document_path.split('/' )[-1] with open(a , encoding='utf-8' ) as source: lowerCAmelCase__ : List[Any] = source.read() lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = process_story(a ) return document_name, story_lines, summary_lines def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> Tuple: lowerCAmelCase__ : Optional[int] = list(filter(lambda SCREAMING_SNAKE_CASE_ : len(SCREAMING_SNAKE_CASE_ ) != 0 , [line.strip() for line in raw_story.split('\n' )] ) ) # for some unknown reason some lines miss a period, add it lowerCAmelCase__ : List[Any] = [_add_missing_period(SCREAMING_SNAKE_CASE_ ) for line in nonempty_lines] # gather article lines lowerCAmelCase__ : int = [] lowerCAmelCase__ : Any = deque(SCREAMING_SNAKE_CASE_ ) while True: try: lowerCAmelCase__ : int = lines.popleft() if element.startswith('@highlight' ): break story_lines.append(SCREAMING_SNAKE_CASE_ ) except IndexError: # if "@highlight" is absent from the file we pop # all elements until there is None, raising an exception. return story_lines, [] # gather summary lines lowerCAmelCase__ : Tuple = list(filter(lambda SCREAMING_SNAKE_CASE_ : not t.startswith('@highlight' ) , SCREAMING_SNAKE_CASE_ ) ) return story_lines, summary_lines def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> Any: lowerCAmelCase__ : int = ['.', '!', '?', '...', '\'', '`', '"', '\u2019', '\u2019', ')'] if line.startswith('@highlight' ): return line if line[-1] in END_TOKENS: return line return line + "." def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: if len(SCREAMING_SNAKE_CASE_ ) > block_size: return sequence[:block_size] else: sequence.extend([pad_token_id] * (block_size - len(SCREAMING_SNAKE_CASE_ )) ) return sequence def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: lowerCAmelCase__ : str = torch.ones_like(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : int = sequence == pad_token_id lowerCAmelCase__ : Optional[int] = 0 return mask def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: lowerCAmelCase__ : Any = [tokenizer.encode(SCREAMING_SNAKE_CASE_ ) for line in story_lines] lowerCAmelCase__ : str = [token for sentence in story_lines_token_ids for token in sentence] lowerCAmelCase__ : Dict = [tokenizer.encode(SCREAMING_SNAKE_CASE_ ) for line in summary_lines] lowerCAmelCase__ : str = [token for sentence in summary_lines_token_ids for token in sentence] return story_token_ids, summary_token_ids def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: lowerCAmelCase__ : Optional[int] = [] for sequence in batch: lowerCAmelCase__ : Union[str, Any] = -1 lowerCAmelCase__ : int = [] for s in sequence: if s == separator_token_id: sentence_num += 1 embeddings.append(sentence_num % 2 ) batch_embeddings.append(SCREAMING_SNAKE_CASE_ ) return torch.tensor(SCREAMING_SNAKE_CASE_ )
69
0
'''simple docstring''' def __UpperCAmelCase ( _UpperCAmelCase : str ) -> int: assert column_title.isupper() __snake_case = 0 __snake_case = len(_UpperCAmelCase ) - 1 __snake_case = 0 while index >= 0: __snake_case = (ord(column_title[index] ) - 64) * pow(26 , _UpperCAmelCase ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
69
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 a : Tuple = get_tests_dir('''fixtures''') a : Dict = get_tests_dir('''fixtures/dummy_feature_extractor_config.json''') a : int = get_tests_dir('''fixtures/dummy-config.json''') class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def A ( self : Tuple ): """simple docstring""" __snake_case = 0 def A ( self : str ): """simple docstring""" __snake_case = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h" ) self.assertIsInstance(a_ , a_ ) def A ( self : str ): """simple docstring""" __snake_case = AutoFeatureExtractor.from_pretrained(a_ ) self.assertIsInstance(a_ , a_ ) def A ( self : str ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: __snake_case = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally __snake_case = AutoFeatureExtractor.from_pretrained(a_ ).to_dict() config_dict.pop("feature_extractor_type" ) __snake_case = WavaVecaFeatureExtractor(**a_ ) # save in new folder model_config.save_pretrained(a_ ) config.save_pretrained(a_ ) __snake_case = AutoFeatureExtractor.from_pretrained(a_ ) # make sure private variable is not incorrectly saved __snake_case = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(a_ , a_ ) def A ( self : List[Any] ): """simple docstring""" __snake_case = AutoFeatureExtractor.from_pretrained(a_ ) self.assertIsInstance(a_ , a_ ) def A ( self : Optional[Any] ): """simple docstring""" with self.assertRaisesRegex( a_ , "bert-base is not a local folder and is not a valid model identifier" ): __snake_case = AutoFeatureExtractor.from_pretrained("bert-base" ) def A ( self : Dict ): """simple docstring""" with self.assertRaisesRegex( a_ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): __snake_case = AutoFeatureExtractor.from_pretrained(a_ , revision="aaaaaa" ) def A ( self : Tuple ): """simple docstring""" with self.assertRaisesRegex( a_ , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): __snake_case = AutoFeatureExtractor.from_pretrained("hf-internal-testing/config-no-model" ) def A ( self : Tuple ): """simple docstring""" with self.assertRaises(a_ ): __snake_case = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(a_ ): __snake_case = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ ) __snake_case = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(a_ ) __snake_case = AutoFeatureExtractor.from_pretrained(a_ , trust_remote_code=a_ ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) def A ( self : int ): """simple docstring""" try: AutoConfig.register("custom" , a_ ) AutoFeatureExtractor.register(a_ , a_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(a_ ): AutoFeatureExtractor.register(a_ , a_ ) # Now that the config is registered, it can be used as any other config with the auto-API __snake_case = CustomFeatureExtractor.from_pretrained(a_ ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(a_ ) __snake_case = AutoFeatureExtractor.from_pretrained(a_ ) self.assertIsInstance(a_ , a_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def A ( self : Dict ): """simple docstring""" class SCREAMING_SNAKE_CASE__ ( _UpperCamelCase ): __SCREAMING_SNAKE_CASE = True try: AutoConfig.register("custom" , a_ ) AutoFeatureExtractor.register(a_ , a_ ) # If remote code is not set, the default is to use local __snake_case = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. __snake_case = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub __snake_case = AutoFeatureExtractor.from_pretrained( "hf-internal-testing/test_dynamic_feature_extractor" , trust_remote_code=a_ ) self.assertEqual(feature_extractor.__class__.__name__ , "NewFeatureExtractor" ) self.assertTrue(not hasattr(a_ , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
69
1
import argparse import os import re import tensorflow as tf import torch from transformers import BertConfig, BertModel from transformers.utils import logging logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) def A_ ( lowercase_ , lowercase_ , lowercase_ ) ->List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = os.path.abspath(lowercase_ ) logger.info(f'''Converting TensorFlow checkpoint from {tf_path}''' ) # Load weights from TF model SCREAMING_SNAKE_CASE = tf.train.list_variables(lowercase_ ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for full_name, shape in init_vars: # logger.info(f"Loading TF weight {name} with shape {shape}") SCREAMING_SNAKE_CASE = full_name.split('/' ) if full_name == "_CHECKPOINTABLE_OBJECT_GRAPH" or name[0] in ["global_step", "save_counter"]: logger.info(f'''Skipping non-model layer {full_name}''' ) continue if "optimizer" in full_name: logger.info(f'''Skipping optimization layer {full_name}''' ) continue if name[0] == "model": # ignore initial 'model' SCREAMING_SNAKE_CASE = name[1:] # figure out how many levels deep the name is SCREAMING_SNAKE_CASE = 0 for _name in name: if _name.startswith('layer_with_weights' ): depth += 1 else: break layer_depth.append(lowercase_ ) # read data SCREAMING_SNAKE_CASE = tf.train.load_variable(lowercase_ , lowercase_ ) names.append('/'.join(lowercase_ ) ) arrays.append(lowercase_ ) logger.info(f'''Read a total of {len(lowercase_ ):,} layers''' ) # Sanity check if len(set(lowercase_ ) ) != 1: raise ValueError(f'''Found layer names with different depths (layer depth {list(set(lowercase_ ) )})''' ) SCREAMING_SNAKE_CASE = list(set(lowercase_ ) )[0] if layer_depth != 1: raise ValueError( 'The model contains more than just the embedding/encoder layers. This script does not handle MLM/NSP' ' heads.' ) # convert layers logger.info('Converting weights...' ) for full_name, array in zip(lowercase_ , lowercase_ ): SCREAMING_SNAKE_CASE = full_name.split('/' ) SCREAMING_SNAKE_CASE = model SCREAMING_SNAKE_CASE = [] for i, m_name in enumerate(lowercase_ ): if m_name == ".ATTRIBUTES": # variable names end with .ATTRIBUTES/VARIABLE_VALUE break if m_name.startswith('layer_with_weights' ): SCREAMING_SNAKE_CASE = int(m_name.split('-' )[-1] ) if layer_num <= 2: # embedding layers # layer_num 0: word_embeddings # layer_num 1: position_embeddings # layer_num 2: token_type_embeddings continue elif layer_num == 3: # embedding LayerNorm trace.extend(['embeddings', 'LayerNorm'] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'embeddings' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'LayerNorm' ) elif layer_num > 3 and layer_num < config.num_hidden_layers + 4: # encoder layers trace.extend(['encoder', 'layer', str(layer_num - 4 )] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'encoder' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'layer' ) SCREAMING_SNAKE_CASE = pointer[layer_num - 4] elif layer_num == config.num_hidden_layers + 4: # pooler layer trace.extend(['pooler', 'dense'] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'pooler' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'dense' ) elif m_name == "embeddings": trace.append('embeddings' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'embeddings' ) if layer_num == 0: trace.append('word_embeddings' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'word_embeddings' ) elif layer_num == 1: trace.append('position_embeddings' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'position_embeddings' ) elif layer_num == 2: trace.append('token_type_embeddings' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'token_type_embeddings' ) else: raise ValueError(f'''Unknown embedding layer with name {full_name}''' ) trace.append('weight' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'weight' ) elif m_name == "_attention_layer": # self-attention layer trace.extend(['attention', 'self'] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'attention' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'self' ) elif m_name == "_attention_layer_norm": # output attention norm trace.extend(['attention', 'output', 'LayerNorm'] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'attention' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'output' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'LayerNorm' ) elif m_name == "_attention_output_dense": # output attention dense trace.extend(['attention', 'output', 'dense'] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'attention' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'output' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'dense' ) elif m_name == "_output_dense": # output dense trace.extend(['output', 'dense'] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'output' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'dense' ) elif m_name == "_output_layer_norm": # output dense trace.extend(['output', 'LayerNorm'] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'output' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'LayerNorm' ) elif m_name == "_key_dense": # attention key trace.append('key' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'key' ) elif m_name == "_query_dense": # attention query trace.append('query' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'query' ) elif m_name == "_value_dense": # attention value trace.append('value' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'value' ) elif m_name == "_intermediate_dense": # attention intermediate dense trace.extend(['intermediate', 'dense'] ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'intermediate' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'dense' ) elif m_name == "_output_layer_norm": # output layer norm trace.append('output' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'output' ) # weights & biases elif m_name in ["bias", "beta"]: trace.append('bias' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'bias' ) elif m_name in ["kernel", "gamma"]: trace.append('weight' ) SCREAMING_SNAKE_CASE = getattr(lowercase_ , 'weight' ) else: logger.warning(f'''Ignored {m_name}''' ) # for certain layers reshape is necessary SCREAMING_SNAKE_CASE = '.'.join(lowercase_ ) if re.match(r'(\S+)\.attention\.self\.(key|value|query)\.(bias|weight)' , lowercase_ ) or re.match( r'(\S+)\.attention\.output\.dense\.weight' , lowercase_ ): SCREAMING_SNAKE_CASE = array.reshape(pointer.data.shape ) if "kernel" in full_name: SCREAMING_SNAKE_CASE = array.transpose() if pointer.shape == array.shape: SCREAMING_SNAKE_CASE = torch.from_numpy(lowercase_ ) else: raise ValueError( f'''Shape mismatch in layer {full_name}: Model expects shape {pointer.shape} but layer contains shape:''' f''' {array.shape}''' ) logger.info(f'''Successfully set variable {full_name} to PyTorch layer {trace}''' ) return model def A_ ( lowercase_ , lowercase_ , lowercase_ ) ->Any: """simple docstring""" logger.info(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE = BertConfig.from_json_file(lowercase_ ) SCREAMING_SNAKE_CASE = BertModel(lowercase_ ) # Load weights from checkpoint logger.info(f'''Loading weights from checkpoint {tf_checkpoint_path}...''' ) load_tfa_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model logger.info(f'''Saving PyTorch model to {pytorch_dump_path}...''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( "--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow 2.x checkpoint path." ) parser.add_argument( "--bert_config_file", type=str, required=True, help="The config json file corresponding to the BERT model. This specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", type=str, required=True, help="Path to the output PyTorch model (must include filename).", ) __UpperCAmelCase = parser.parse_args() convert_tfa_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
259
import numpy as np class a_: """simple docstring""" def __init__( self : Any) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE = (0, 0) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 def __eq__( self : int , lowerCAmelCase__ : List[Any]) -> Optional[int]: """simple docstring""" return self.position == cell.position def __UpperCamelCase ( self : int) -> int: """simple docstring""" print(self.position) class a_: """simple docstring""" def __init__( self : Optional[int] , lowerCAmelCase__ : List[str]=(5, 5)) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE = np.zeros(lowerCAmelCase__) SCREAMING_SNAKE_CASE = world_size[0] SCREAMING_SNAKE_CASE = world_size[1] def __UpperCamelCase ( self : Optional[Any]) -> Tuple: """simple docstring""" print(self.w) def __UpperCamelCase ( self : Union[str, Any] , lowerCAmelCase__ : Tuple) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] SCREAMING_SNAKE_CASE = cell.position[0] SCREAMING_SNAKE_CASE = cell.position[1] SCREAMING_SNAKE_CASE = [] for n in neughbour_cord: SCREAMING_SNAKE_CASE = current_x + n[0] SCREAMING_SNAKE_CASE = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: SCREAMING_SNAKE_CASE = Cell() SCREAMING_SNAKE_CASE = (x, y) SCREAMING_SNAKE_CASE = cell neighbours.append(lowerCAmelCase__) return neighbours def A_ ( lowercase_ , lowercase_ , lowercase_ ) ->Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] _open.append(lowercase_ ) while _open: SCREAMING_SNAKE_CASE = np.argmin([n.f for n in _open] ) SCREAMING_SNAKE_CASE = _open[min_f] _closed.append(_open.pop(lowercase_ ) ) if current == goal: break for n in world.get_neigbours(lowercase_ ): for c in _closed: if c == n: continue SCREAMING_SNAKE_CASE = current.g + 1 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = n.position SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = goal.position SCREAMING_SNAKE_CASE = (ya - ya) ** 2 + (xa - xa) ** 2 SCREAMING_SNAKE_CASE = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(lowercase_ ) SCREAMING_SNAKE_CASE = [] while current.parent is not None: path.append(current.position ) SCREAMING_SNAKE_CASE = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": __UpperCAmelCase = Gridworld() # Start position and goal __UpperCAmelCase = Cell() __UpperCAmelCase = (0, 0) __UpperCAmelCase = Cell() __UpperCAmelCase = (4, 4) print(f'path from {start.position} to {goal.position}') __UpperCAmelCase = astar(world, start, goal) # Just for visual reasons. for i in s: __UpperCAmelCase = 1 print(world.w)
259
1
import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def a_ ( UpperCamelCase_ : str ) -> int: """simple docstring""" return EnvironmentCommand() class lowerCAmelCase ( __UpperCamelCase ): '''simple docstring''' @staticmethod def lowerCamelCase__ ( __snake_case : ArgumentParser ) -> Dict: '''simple docstring''' lowerCamelCase = parser.add_parser('env' ) download_parser.set_defaults(func=__snake_case ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: '''simple docstring''' lowerCamelCase = huggingface_hub.__version__ lowerCamelCase = 'not installed' lowerCamelCase = 'NA' if is_torch_available(): import torch lowerCamelCase = torch.__version__ lowerCamelCase = torch.cuda.is_available() lowerCamelCase = 'not installed' if is_transformers_available(): import transformers lowerCamelCase = transformers.__version__ lowerCamelCase = 'not installed' if is_accelerate_available(): import accelerate lowerCamelCase = accelerate.__version__ lowerCamelCase = 'not installed' if is_xformers_available(): import xformers lowerCamelCase = xformers.__version__ lowerCamelCase = { '`diffusers` version': version, 'Platform': platform.platform(), 'Python version': platform.python_version(), 'PyTorch version (GPU?)': F'''{pt_version} ({pt_cuda_available})''', 'Huggingface_hub version': hub_version, 'Transformers version': transformers_version, 'Accelerate version': accelerate_version, 'xFormers version': xformers_version, 'Using GPU in script?': '<fill in>', 'Using distributed or parallel set-up in script?': '<fill in>', } print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n' ) print(self.format_dict(__snake_case ) ) return info @staticmethod def lowerCamelCase__ ( __snake_case : Optional[Any] ) -> Tuple: '''simple docstring''' return "\n".join([F'''- {prop}: {val}''' for prop, val in d.items()] ) + "\n"
246
from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class lowerCAmelCase : '''simple docstring''' def __init__( self : Dict , __snake_case : Tuple , __snake_case : Optional[int]=13 , __snake_case : int=7 , __snake_case : Tuple=True , __snake_case : Optional[Any]=True , __snake_case : List[Any]=True , __snake_case : Optional[Any]=True , __snake_case : Optional[Any]=99 , __snake_case : Union[str, Any]=32 , __snake_case : str=2 , __snake_case : Tuple=4 , __snake_case : Tuple=37 , __snake_case : Any="gelu" , __snake_case : List[Any]=0.1 , __snake_case : Optional[int]=0.1 , __snake_case : Tuple=512 , __snake_case : str=16 , __snake_case : str=2 , __snake_case : Dict=0.02 , __snake_case : Union[str, Any]=False , __snake_case : Tuple=True , __snake_case : Union[str, Any]="None" , __snake_case : Union[str, Any]=3 , __snake_case : Optional[Any]=4 , __snake_case : List[str]=None , ) -> Dict: '''simple docstring''' lowerCamelCase = parent lowerCamelCase = batch_size lowerCamelCase = seq_length lowerCamelCase = is_training lowerCamelCase = use_input_mask lowerCamelCase = use_token_type_ids lowerCamelCase = use_labels lowerCamelCase = vocab_size lowerCamelCase = hidden_size lowerCamelCase = num_hidden_layers lowerCamelCase = num_attention_heads lowerCamelCase = intermediate_size lowerCamelCase = hidden_act lowerCamelCase = hidden_dropout_prob lowerCamelCase = attention_probs_dropout_prob lowerCamelCase = max_position_embeddings lowerCamelCase = type_vocab_size lowerCamelCase = type_sequence_label_size lowerCamelCase = initializer_range lowerCamelCase = num_labels lowerCamelCase = num_choices lowerCamelCase = relative_attention lowerCamelCase = position_biased_input lowerCamelCase = pos_att_type lowerCamelCase = scope def lowerCamelCase__ ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase = None if self.use_input_mask: lowerCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase = None if self.use_token_type_ids: lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase = None lowerCamelCase = None lowerCamelCase = None if self.use_labels: lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase = DebertaVaConfig( 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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , initializer_range=self.initializer_range , return_dict=__snake_case , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : Optional[Any] , __snake_case : List[str] , __snake_case : Optional[Any] , __snake_case : Optional[Any] , __snake_case : str , __snake_case : Tuple , __snake_case : List[Any] , __snake_case : Optional[Any] ) -> Any: '''simple docstring''' lowerCamelCase = TFDebertaVaModel(config=__snake_case ) lowerCamelCase = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} lowerCamelCase = [input_ids, input_mask] lowerCamelCase = model(__snake_case ) lowerCamelCase = model(__snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : int , __snake_case : Optional[int] , __snake_case : str , __snake_case : Any , __snake_case : List[str] , __snake_case : Optional[int] , __snake_case : Optional[int] , __snake_case : Union[str, Any] ) -> Any: '''simple docstring''' lowerCamelCase = TFDebertaVaForMaskedLM(config=__snake_case ) lowerCamelCase = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } lowerCamelCase = model(__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase__ ( self : Optional[int] , __snake_case : str , __snake_case : Union[str, Any] , __snake_case : Optional[Any] , __snake_case : List[Any] , __snake_case : Optional[Any] , __snake_case : Dict , __snake_case : Union[str, Any] ) -> List[Any]: '''simple docstring''' lowerCamelCase = self.num_labels lowerCamelCase = TFDebertaVaForSequenceClassification(config=__snake_case ) lowerCamelCase = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } lowerCamelCase = model(__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : Tuple , __snake_case : List[Any] , __snake_case : Optional[Any] , __snake_case : Optional[Any] , __snake_case : Optional[int] , __snake_case : Dict , __snake_case : str , __snake_case : List[str] ) -> int: '''simple docstring''' lowerCamelCase = self.num_labels lowerCamelCase = TFDebertaVaForTokenClassification(config=__snake_case ) lowerCamelCase = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } lowerCamelCase = model(__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase__ ( self : Tuple , __snake_case : Dict , __snake_case : str , __snake_case : Tuple , __snake_case : str , __snake_case : List[str] , __snake_case : int , __snake_case : Any ) -> Dict: '''simple docstring''' lowerCamelCase = TFDebertaVaForQuestionAnswering(config=__snake_case ) lowerCamelCase = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } lowerCamelCase = model(__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 lowerCamelCase__ ( self : Any ) -> List[Any]: '''simple docstring''' lowerCamelCase = self.prepare_config_and_inputs() ( ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ( lowerCamelCase ) , ) = config_and_inputs lowerCamelCase = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' snake_case = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) snake_case = ( { 'feature-extraction': TFDebertaVaModel, 'fill-mask': TFDebertaVaForMaskedLM, 'question-answering': TFDebertaVaForQuestionAnswering, 'text-classification': TFDebertaVaForSequenceClassification, 'token-classification': TFDebertaVaForTokenClassification, 'zero-shot': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) snake_case = False snake_case = False def lowerCamelCase__ ( self : List[Any] ) -> List[str]: '''simple docstring''' lowerCamelCase = TFDebertaVaModelTester(self ) lowerCamelCase = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' self.config_tester.run_common_tests() def lowerCamelCase__ ( self : List[Any] ) -> Tuple: '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def lowerCamelCase__ ( self : int ) -> Union[str, Any]: '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__snake_case ) def lowerCamelCase__ ( self : Tuple ) -> List[str]: '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__snake_case ) def lowerCamelCase__ ( self : Optional[Any] ) -> Tuple: '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__snake_case ) def lowerCamelCase__ ( self : Tuple ) -> str: '''simple docstring''' lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__snake_case ) @slow def lowerCamelCase__ ( self : Dict ) -> List[str]: '''simple docstring''' lowerCamelCase = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) self.assertIsNotNone(__snake_case ) @require_tf class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason='Model not available yet' ) def lowerCamelCase__ ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' pass @slow def lowerCamelCase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' lowerCamelCase = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) lowerCamelCase = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]] ) lowerCamelCase = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) lowerCamelCase = model(__snake_case , attention_mask=__snake_case )[0] lowerCamelCase = tf.constant( [[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] , __snake_case , atol=1e-4 )
246
1
"""simple docstring""" import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _a : List[str] = logging.get_logger(__name__) _a : Tuple = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] _a : Optional[int] = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def a__ ( a : Optional[int] ): """simple docstring""" _snake_case : Any = torch.load(UpperCamelCase__ , map_location="cpu" ) return sd def a__ ( a : Optional[int] , a : Union[str, Any] , a : Dict=rename_keys_prefix ): """simple docstring""" _snake_case : Tuple = OrderedDict() _snake_case : List[Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue _snake_case : Union[str, Any] = key for name_pair in rename_keys_prefix: _snake_case : Optional[int] = new_key.replace(name_pair[0] , name_pair[1] ) _snake_case : List[str] = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately _snake_case : Tuple = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def a__ ( a : Any , a : Dict ): """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), f'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: _snake_case : Any = "pretraining" if "vcr" in checkpoint_path: _snake_case : List[Any] = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: _snake_case : Any = {"visual_embedding_dim": 2_048} elif "vqa" in checkpoint_path: _snake_case : Any = {"visual_embedding_dim": 2_048} elif "nlvr" in checkpoint_path: _snake_case : Optional[Any] = {"visual_embedding_dim": 1_024} else: raise NotImplementedError(f'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: _snake_case : Union[str, Any] = {"visual_embedding_dim": 512} _snake_case : Tuple = "multichoice" elif "vqa_advanced" in checkpoint_path: _snake_case : List[str] = {"visual_embedding_dim": 2_048} _snake_case : List[str] = "vqa_advanced" elif "vqa" in checkpoint_path: _snake_case : List[Any] = {"visual_embedding_dim": 2_048, "num_labels": 3_129} _snake_case : List[str] = "vqa" elif "nlvr" in checkpoint_path: _snake_case : List[Any] = { "visual_embedding_dim": 1_024, "num_labels": 2, } _snake_case : Any = "nlvr" _snake_case : Tuple = VisualBertConfig(**UpperCamelCase__ ) # Load State Dict _snake_case : Dict = load_state_dict(UpperCamelCase__ ) _snake_case : Any = get_new_dict(UpperCamelCase__ , UpperCamelCase__ ) if model_type == "pretraining": _snake_case : List[Any] = VisualBertForPreTraining(UpperCamelCase__ ) elif model_type == "vqa": _snake_case : Optional[Any] = VisualBertForQuestionAnswering(UpperCamelCase__ ) elif model_type == "nlvr": _snake_case : Dict = VisualBertForVisualReasoning(UpperCamelCase__ ) elif model_type == "multichoice": _snake_case : Tuple = VisualBertForMultipleChoice(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) # Save Checkpoints Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _a : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") _a : List[Any] = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
719
"""simple docstring""" from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": _a : Dict = input("""Enter image url: """).strip() print(f'Downloading image from {url} ...') _a : str = BeautifulSoup(requests.get(url).content, """html.parser""") # The image URL is in the content field of the first meta tag with property og:image _a : str = soup.find("""meta""", {"""property""": """og:image"""})["""content"""] _a : Dict = requests.get(image_url).content _a : str = f'{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg' with open(file_name, """wb""") as fp: fp.write(image_data) print(f'Done. Image saved to disk as {file_name}.')
87
0
"""simple docstring""" def SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ ) -> Optional[int]: lowerCAmelCase__ : str = len(lowerCAmelCase__ ) lowerCAmelCase__ : Any = [[False] * (required_sum + 1) for _ in range(arr_len + 1 )] # for each arr value, a sum of zero(0) can be formed by not taking any element # hence True/1 for i in range(arr_len + 1 ): lowerCAmelCase__ : List[str] = True # sum is not zero and set is empty then false for i in range(1 , required_sum + 1 ): lowerCAmelCase__ : List[Any] = False for i in range(1 , arr_len + 1 ): for j in range(1 , required_sum + 1 ): if arr[i - 1] > j: lowerCAmelCase__ : Optional[Any] = subset[i - 1][j] if arr[i - 1] <= j: lowerCAmelCase__ : str = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]] return subset[arr_len][required_sum] if __name__ == "__main__": import doctest doctest.testmod()
453
"""simple docstring""" # NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline # noqa: F401 deprecate( '''stable diffusion controlnet''', '''0.22.0''', '''Importing `FlaxStableDiffusionControlNetPipeline` from diffusers.pipelines.stable_diffusion.flax_pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import FlaxStableDiffusionControlNetPipeline` instead.''', standard_warn=False, stacklevel=3, )
260
0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> list: lowerCAmelCase__ : Any = [0] * len(SCREAMING_SNAKE_CASE_ ) for i in range(1 , len(SCREAMING_SNAKE_CASE_ ) ): # use last results for better performance - dynamic programming lowerCAmelCase__ : Optional[int] = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: lowerCAmelCase__ : Union[str, Any] = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 lowerCAmelCase__ : Any = j return prefix_result def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> int: return max(prefix_function(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": import doctest doctest.testmod()
69
import json import os import unittest from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class A__ ( __magic_name__ , unittest.TestCase ): lowercase = XLMTokenizer lowercase = False def _lowerCamelCase ( self : int ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase__ : List[str] = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] lowerCAmelCase__ : Any = dict(zip(a , range(len(a ) ) ) ) lowerCAmelCase__ : Optional[int] = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] lowerCAmelCase__ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) lowerCAmelCase__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' ) as fp: fp.write(json.dumps(a ) ) with open(self.merges_file , 'w' ) as fp: fp.write('\n'.join(a ) ) def _lowerCamelCase ( self : List[str] , a : Dict ): '''simple docstring''' lowerCAmelCase__ : List[Any] = 'lower newer' lowerCAmelCase__ : Any = 'lower newer' return input_text, output_text def _lowerCamelCase ( self : int ): '''simple docstring''' lowerCAmelCase__ : Tuple = XLMTokenizer(self.vocab_file , self.merges_file ) lowerCAmelCase__ : Optional[int] = 'lower' lowerCAmelCase__ : Optional[Any] = ['low', 'er</w>'] lowerCAmelCase__ : Dict = tokenizer.tokenize(a ) self.assertListEqual(a , a ) lowerCAmelCase__ : Tuple = tokens + ['<unk>'] lowerCAmelCase__ : Optional[int] = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @slow def _lowerCamelCase ( self : Any ): '''simple docstring''' lowerCAmelCase__ : List[Any] = XLMTokenizer.from_pretrained('xlm-mlm-en-2048' ) lowerCAmelCase__ : Any = tokenizer.encode('sequence builders' , add_special_tokens=a ) lowerCAmelCase__ : Union[str, Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=a ) lowerCAmelCase__ : List[Any] = tokenizer.build_inputs_with_special_tokens(a ) lowerCAmelCase__ : List[str] = tokenizer.build_inputs_with_special_tokens(a , a ) assert encoded_sentence == [0] + text + [1] assert encoded_pair == [0] + text + [1] + text_a + [1]
69
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a_ = { """configuration_conditional_detr""": [ """CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ConditionalDetrConfig""", """ConditionalDetrOnnxConfig""", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ["""ConditionalDetrFeatureExtractor"""] a_ = ["""ConditionalDetrImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ """CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST""", """ConditionalDetrForObjectDetection""", """ConditionalDetrForSegmentation""", """ConditionalDetrModel""", """ConditionalDetrPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
437
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { """microsoft/xprophetnet-large-wiki100-cased""": ( """https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json""" ), } class A_(SCREAMING_SNAKE_CASE_ ): """simple docstring""" a_ : List[Any] = """xlm-prophetnet""" a_ : Any = ["""past_key_values"""] a_ : Optional[int] = { """num_attention_heads""": """num_encoder_attention_heads""", } def __init__( self , A = 0.1 , A = "gelu" , A = 3_0522 , A = 1024 , A = 4096 , A = 12 , A = 16 , A = 4096 , A = 12 , A = 16 , A = 0.1 , A = 0.1 , A = 512 , A = 0.0_2 , A = True , A = True , A = 0 , A = 2 , A = 32 , A = 128 , A = False , A = 0.0 , A = True , A = 0 , A = 1 , A = 2 , **A , ): _lowerCamelCase : Dict = vocab_size _lowerCamelCase : List[Any] = hidden_size _lowerCamelCase : List[Any] = encoder_ffn_dim _lowerCamelCase : Any = num_encoder_layers _lowerCamelCase : Any = num_encoder_attention_heads _lowerCamelCase : List[str] = decoder_ffn_dim _lowerCamelCase : Optional[int] = num_decoder_layers _lowerCamelCase : List[str] = num_decoder_attention_heads _lowerCamelCase : Optional[Any] = max_position_embeddings _lowerCamelCase : Optional[Any] = init_std # Normal(0, this parameter) _lowerCamelCase : Optional[int] = activation_function # parameters for xlmprophetnet _lowerCamelCase : Any = ngram _lowerCamelCase : Dict = num_buckets _lowerCamelCase : Dict = relative_max_distance _lowerCamelCase : Optional[Any] = disable_ngram_loss _lowerCamelCase : Union[str, Any] = eps # 3 Types of Dropout _lowerCamelCase : int = attention_dropout _lowerCamelCase : str = activation_dropout _lowerCamelCase : Optional[int] = dropout _lowerCamelCase : List[Any] = use_cache super().__init__( pad_token_id=A , bos_token_id=A , eos_token_id=A , is_encoder_decoder=A , add_cross_attention=A , decoder_start_token_id=A , **A , ) @property def _lowerCAmelCase ( self ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def _lowerCAmelCase ( self , A ): raise NotImplementedError( 'This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and' ' `num_decoder_layers`.' )
437
1
from __future__ import annotations snake_case__ : Tuple = [ [-1, 0], # left [0, -1], # down [1, 0], # right [0, 1], # up ] def snake_case_ ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ): __lowercase = [ [0 for col in range(len(grid[0] ) )] for row in range(len(_SCREAMING_SNAKE_CASE ) ) ] # the reference grid __lowercase = 1 __lowercase = [ [0 for col in range(len(grid[0] ) )] for row in range(len(_SCREAMING_SNAKE_CASE ) ) ] # the action grid __lowercase = init[0] __lowercase = init[1] __lowercase = 0 __lowercase = g + heuristic[x][y] # cost from starting cell to destination cell __lowercase = [[f, g, x, y]] __lowercase = False # flag that is set when search is complete __lowercase = False # flag set if we can't find expand while not found and not resign: if len(_SCREAMING_SNAKE_CASE ) == 0: raise ValueError("Algorithm is unable to find solution" ) else: # to choose the least costliest action so as to move closer to the goal cell.sort() cell.reverse() __lowercase = cell.pop() __lowercase = next_cell[2] __lowercase = next_cell[3] __lowercase = next_cell[1] if x == goal[0] and y == goal[1]: __lowercase = True else: for i in range(len(_SCREAMING_SNAKE_CASE ) ): # to try out different valid actions __lowercase = x + DIRECTIONS[i][0] __lowercase = y + DIRECTIONS[i][1] if xa >= 0 and xa < len(_SCREAMING_SNAKE_CASE ) and ya >= 0 and ya < len(grid[0] ): if closed[xa][ya] == 0 and grid[xa][ya] == 0: __lowercase = g + cost __lowercase = ga + heuristic[xa][ya] cell.append([fa, ga, xa, ya] ) __lowercase = 1 __lowercase = i __lowercase = [] __lowercase = goal[0] __lowercase = goal[1] invpath.append([x, y] ) # we get the reverse path from here while x != init[0] or y != init[1]: __lowercase = x - DIRECTIONS[action[x][y]][0] __lowercase = y - DIRECTIONS[action[x][y]][1] __lowercase = xa __lowercase = ya invpath.append([x, y] ) __lowercase = [] for i in range(len(_SCREAMING_SNAKE_CASE ) ): path.append(invpath[len(_SCREAMING_SNAKE_CASE ) - 1 - i] ) return path, action if __name__ == "__main__": snake_case__ : List[str] = [ [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0], ] snake_case__ : Optional[int] = [0, 0] # all coordinates are given in format [y,x] snake_case__ : Union[str, Any] = [len(grid) - 1, len(grid[0]) - 1] snake_case__ : Dict = 1 # the cost map which pushes the path closer to the goal snake_case__ : Tuple = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): snake_case__ : Optional[int] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: # added extra penalty in the heuristic map snake_case__ : List[Any] = 99 snake_case__ , snake_case__ : Union[str, Any] = search(grid, init, goal, cost, heuristic) print("""ACTION MAP""") for i in range(len(action)): print(action[i]) for i in range(len(path)): print(path[i])
655
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class _A ( _lowercase , _lowercase ): '''simple docstring''' @register_to_config def __init__( self : Optional[Any] , *, lowerCamelCase : int = 4 , lowerCamelCase : int = 768 , lowerCamelCase : int , lowerCamelCase : Optional[int] , ): '''simple docstring''' super().__init__() __lowercase = nn.Parameter(torch.zeros(lowerCamelCase ) ) # parameters for additional clip time embeddings __lowercase = nn.Linear(lowerCamelCase , lowerCamelCase ) __lowercase = nn.Linear(lowerCamelCase , lowerCamelCase ) # parameters for encoder hidden states __lowercase = clip_extra_context_tokens __lowercase = nn.Linear( lowerCamelCase , self.clip_extra_context_tokens * cross_attention_dim ) __lowercase = nn.Linear(lowerCamelCase , lowerCamelCase ) __lowercase = nn.LayerNorm(lowerCamelCase ) def _snake_case ( self : Union[str, Any] , *, lowerCamelCase : Any , lowerCamelCase : Tuple , lowerCamelCase : Optional[int] , lowerCamelCase : Tuple ): '''simple docstring''' if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings __lowercase = image_embeddings.shape[0] __lowercase = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) __lowercase = classifier_free_guidance_embeddings.expand( lowerCamelCase , -1 ) __lowercase = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] __lowercase = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... __lowercase = self.embedding_proj(lowerCamelCase ) __lowercase = self.clip_image_embeddings_project_to_time_embeddings(lowerCamelCase ) __lowercase = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" __lowercase = self.clip_extra_context_tokens_proj(lowerCamelCase ) __lowercase = clip_extra_context_tokens.reshape(lowerCamelCase , -1 , self.clip_extra_context_tokens ) __lowercase = clip_extra_context_tokens.permute(0 , 2 , 1 ) __lowercase = self.encoder_hidden_states_proj(lowerCamelCase ) __lowercase = self.text_encoder_hidden_states_norm(lowerCamelCase ) __lowercase = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
655
1
from math import factorial def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : int = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] =2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[Any] =n // 2 return int(factorial(lowerCAmelCase_ ) / (factorial(lowerCAmelCase_ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: __SCREAMING_SNAKE_CASE = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number.')
220
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=__A ) class lowerCAmelCase_ ( __A ): '''simple docstring''' _lowercase = field(default='text-classification' , metadata={'include_in_asdict_even_if_is_default': True} ) _lowercase = Features({'text': Value('string' )} ) _lowercase = Features({'labels': ClassLabel} ) _lowercase = "text" _lowercase = "labels" def __lowerCamelCase ( self , __UpperCAmelCase ): if self.label_column not in features: raise ValueError(F"""Column {self.label_column} is not present in features.""" ) if not isinstance(features[self.label_column] , __UpperCAmelCase ): raise ValueError(F"""Column {self.label_column} is not a ClassLabel.""" ) SCREAMING_SNAKE_CASE_ : Optional[int] =copy.deepcopy(self ) SCREAMING_SNAKE_CASE_ : Any =self.label_schema.copy() SCREAMING_SNAKE_CASE_ : Any =features[self.label_column] SCREAMING_SNAKE_CASE_ : int =label_schema return task_template @property def __lowerCamelCase ( self ): return { self.text_column: "text", self.label_column: "labels", }
220
1
'''simple docstring''' from math import sqrt def UpperCamelCase__ ( a__ ): '''simple docstring''' _lowerCAmelCase =0 for i in range(1 , int(sqrt(a__ ) + 1 ) ): if n % i == 0 and i != sqrt(a__ ): total += i + n // i elif i == sqrt(a__ ): total += i return total - n def UpperCamelCase__ ( a__ = 1_0_0_0_0 ): '''simple docstring''' _lowerCAmelCase =sum( i for i in range(1 , a__ ) if sum_of_divisors(sum_of_divisors(a__ ) ) == i and sum_of_divisors(a__ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
58
'''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 lowercase_ = logging.getLogger(__name__) class SCREAMING_SNAKE_CASE ( __lowercase): """simple docstring""" lowercase : int = 'sequence-classification' def __init__( self , __A ) -> List[Any]: if type(__A ) == dict: _lowerCAmelCase =Namespace(**__A ) _lowerCAmelCase =glue_output_modes[hparams.task] _lowerCAmelCase =glue_tasks_num_labels[hparams.task] super().__init__(__A , __A , self.mode ) def UpperCamelCase__ ( self , **__A ) -> Any: return self.model(**__A ) def UpperCamelCase__ ( self , __A , __A ) -> Union[str, Any]: _lowerCAmelCase ={'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type not in ["distilbert", "bart"]: _lowerCAmelCase =batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None _lowerCAmelCase =self(**__A ) _lowerCAmelCase =outputs[0] _lowerCAmelCase =self.trainer.lr_schedulers[0]['scheduler'] _lowerCAmelCase ={'loss': loss, 'rate': lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def UpperCamelCase__ ( self ) -> Any: _lowerCAmelCase =self.hparams _lowerCAmelCase =processors[args.task]() _lowerCAmelCase =processor.get_labels() for mode in ["train", "dev"]: _lowerCAmelCase =self._feature_file(__A ) if os.path.exists(__A ) and not args.overwrite_cache: logger.info('Loading features from cached file %s' , __A ) else: logger.info('Creating features from dataset file at %s' , args.data_dir ) _lowerCAmelCase =( processor.get_dev_examples(args.data_dir ) if mode == 'dev' else processor.get_train_examples(args.data_dir ) ) _lowerCAmelCase =convert_examples_to_features( __A , 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' , __A ) torch.save(__A , __A ) def UpperCamelCase__ ( self , __A , __A , __A = False ) -> DataLoader: _lowerCAmelCase ='dev' if mode == 'test' else mode _lowerCAmelCase =self._feature_file(__A ) logger.info('Loading features from cached file %s' , __A ) _lowerCAmelCase =torch.load(__A ) _lowerCAmelCase =torch.tensor([f.input_ids for f in features] , dtype=torch.long ) _lowerCAmelCase =torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) _lowerCAmelCase =torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": _lowerCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": _lowerCAmelCase =torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(__A , __A , __A , __A ) , batch_size=__A , shuffle=__A , ) def UpperCamelCase__ ( self , __A , __A ) -> List[str]: _lowerCAmelCase ={'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} if self.config.model_type not in ["distilbert", "bart"]: _lowerCAmelCase =batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None _lowerCAmelCase =self(**__A ) _lowerCAmelCase , _lowerCAmelCase =outputs[:2] _lowerCAmelCase =logits.detach().cpu().numpy() _lowerCAmelCase =inputs['labels'].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def UpperCamelCase__ ( self , __A ) -> tuple: _lowerCAmelCase =torch.stack([x['val_loss'] for x in outputs] ).mean().detach().cpu().item() _lowerCAmelCase =np.concatenate([x['pred'] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": _lowerCAmelCase =np.argmax(__A , axis=1 ) elif self.hparams.glue_output_mode == "regression": _lowerCAmelCase =np.squeeze(__A ) _lowerCAmelCase =np.concatenate([x['target'] for x in outputs] , axis=0 ) _lowerCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] _lowerCAmelCase =[[] for _ in range(out_label_ids.shape[0] )] _lowerCAmelCase ={**{'val_loss': val_loss_mean}, **compute_metrics(self.hparams.task , __A , __A )} _lowerCAmelCase =dict(results.items() ) _lowerCAmelCase =results return ret, preds_list, out_label_list def UpperCamelCase__ ( self , __A ) -> dict: _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase =self._eval_end(__A ) _lowerCAmelCase =ret['log'] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def UpperCamelCase__ ( self , __A ) -> dict: _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase =self._eval_end(__A ) _lowerCAmelCase =ret['log'] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def UpperCamelCase__ ( __A , __A ) -> Any: BaseTransformer.add_model_specific_args(__A , __A ) parser.add_argument( '--max_seq_length' , default=128 , type=__A , 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=__A , required=__A , help='The GLUE task to run' , ) parser.add_argument( '--gpus' , default=0 , type=__A , 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''' _lowerCAmelCase =argparse.ArgumentParser() add_generic_args(a__ , os.getcwd() ) _lowerCAmelCase =GLUETransformer.add_model_specific_args(a__ , os.getcwd() ) _lowerCAmelCase =parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: _lowerCAmelCase =os.path.join( './results' , F'''{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}''' , ) os.makedirs(args.output_dir ) _lowerCAmelCase =GLUETransformer(a__ ) _lowerCAmelCase =generic_train(a__ , a__ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: _lowerCAmelCase =sorted(glob.glob(os.path.join(args.output_dir , 'checkpoint-epoch=*.ckpt' ) , recursive=a__ ) ) _lowerCAmelCase =model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(a__ ) if __name__ == "__main__": main()
58
1
"""simple docstring""" import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class A__: @staticmethod def _a ( *__SCREAMING_SNAKE_CASE : str , **__SCREAMING_SNAKE_CASE : str ) -> List[str]: """simple docstring""" pass def _a ( UpperCAmelCase__ ) -> Any: return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. lowerCAmelCase__ =( "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png" ) @is_pipeline_test @require_torch @require_vision class A__( unittest.TestCase ): lowerCAmelCase = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def _a ( self : Tuple , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline( '''document-question-answering''' , model=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , image_processor=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = INVOICE_URL __SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , '''''' ) ) ) __SCREAMING_SNAKE_CASE = '''What is the placebo?''' __SCREAMING_SNAKE_CASE = [ { '''image''': load_image(__SCREAMING_SNAKE_CASE ), '''question''': question, }, { '''image''': image, '''question''': question, }, { '''image''': image, '''question''': question, '''word_boxes''': word_boxes, }, ] return dqa_pipeline, examples def _a ( self : str , __SCREAMING_SNAKE_CASE : Optional[int] , __SCREAMING_SNAKE_CASE : Union[str, Any] ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = dqa_pipeline(__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( __SCREAMING_SNAKE_CASE , [ [ {'''score''': ANY(__SCREAMING_SNAKE_CASE ), '''answer''': ANY(__SCREAMING_SNAKE_CASE ), '''start''': ANY(__SCREAMING_SNAKE_CASE ), '''end''': ANY(__SCREAMING_SNAKE_CASE )}, {'''score''': ANY(__SCREAMING_SNAKE_CASE ), '''answer''': ANY(__SCREAMING_SNAKE_CASE ), '''start''': ANY(__SCREAMING_SNAKE_CASE ), '''end''': ANY(__SCREAMING_SNAKE_CASE )}, ] ] * 3 , ) @require_torch @require_detectrona @require_pytesseract def _a ( self : List[str] ) -> Dict: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline('''document-question-answering''' , model='''hf-internal-testing/tiny-random-layoutlmv2''' ) __SCREAMING_SNAKE_CASE = INVOICE_URL __SCREAMING_SNAKE_CASE = '''How many cats are there?''' __SCREAMING_SNAKE_CASE = [ {'''score''': 0.00_01, '''answer''': '''oy 2312/2019''', '''start''': 38, '''end''': 39}, {'''score''': 0.00_01, '''answer''': '''oy 2312/2019 DUE''', '''start''': 38, '''end''': 40}, ] __SCREAMING_SNAKE_CASE = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , __SCREAMING_SNAKE_CASE ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably __SCREAMING_SNAKE_CASE = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' __SCREAMING_SNAKE_CASE = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual(__SCREAMING_SNAKE_CASE , [] ) # We can optionnally pass directly the words and bounding boxes __SCREAMING_SNAKE_CASE = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , words=__SCREAMING_SNAKE_CASE , boxes=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual(__SCREAMING_SNAKE_CASE , [] ) @slow @require_torch @require_detectrona @require_pytesseract def _a ( self : int ) -> int: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline( '''document-question-answering''' , model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''' , revision='''9977165''' , ) __SCREAMING_SNAKE_CASE = INVOICE_URL __SCREAMING_SNAKE_CASE = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ] * 2 , ) @slow @require_torch @require_detectrona @require_pytesseract def _a ( self : Dict ) -> Tuple: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline( '''document-question-answering''' , model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''' , revision='''9977165''' , max_seq_len=50 , ) __SCREAMING_SNAKE_CASE = INVOICE_URL __SCREAMING_SNAKE_CASE = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] ] * 2 , ) @slow @require_torch @require_pytesseract @require_vision def _a ( self : Optional[Any] ) -> str: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( '''impira/layoutlm-document-qa''' , revision='''3dc6de3''' , add_prefix_space=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipeline( '''document-question-answering''' , model='''impira/layoutlm-document-qa''' , tokenizer=__SCREAMING_SNAKE_CASE , revision='''3dc6de3''' , ) __SCREAMING_SNAKE_CASE = INVOICE_URL __SCREAMING_SNAKE_CASE = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] , ) __SCREAMING_SNAKE_CASE = dqa_pipeline({'''image''': image, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] , ) __SCREAMING_SNAKE_CASE = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] ] * 2 , ) __SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , '''''' ) ) ) # This model should also work if `image` is set to None __SCREAMING_SNAKE_CASE = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] , ) @slow @require_torch @require_pytesseract @require_vision def _a ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained( '''impira/layoutlm-document-qa''' , revision='''3dc6de3''' , add_prefix_space=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE = pipeline( '''document-question-answering''' , model='''impira/layoutlm-document-qa''' , tokenizer=__SCREAMING_SNAKE_CASE , revision='''3dc6de3''' , max_seq_len=50 , ) __SCREAMING_SNAKE_CASE = INVOICE_URL __SCREAMING_SNAKE_CASE = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) __SCREAMING_SNAKE_CASE = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}] , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ [ {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] ] * 2 , ) __SCREAMING_SNAKE_CASE = list(zip(*apply_tesseract(load_image(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE , '''''' ) ) ) # This model should also work if `image` is set to None __SCREAMING_SNAKE_CASE = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question} , top_k=2 ) self.assertEqual( nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [ {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] , ) @slow @require_torch def _a ( self : str ) -> Optional[int]: """simple docstring""" __SCREAMING_SNAKE_CASE = pipeline( '''document-question-answering''' , model='''naver-clova-ix/donut-base-finetuned-docvqa''' , tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa''' ) , feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa''' , ) __SCREAMING_SNAKE_CASE = INVOICE_URL __SCREAMING_SNAKE_CASE = '''What is the invoice number?''' __SCREAMING_SNAKE_CASE = dqa_pipeline(image=__SCREAMING_SNAKE_CASE , question=__SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual(nested_simplify(__SCREAMING_SNAKE_CASE , decimals=4 ) , [{'''answer''': '''us-001'''}] ) @require_tf @unittest.skip('''Document question answering not implemented in TF''' ) def _a ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" pass
482
"""simple docstring""" from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES lowerCAmelCase__ =logging.get_logger(__name__) lowerCAmelCase__ =OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) lowerCAmelCase__ =OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) lowerCAmelCase__ =OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) lowerCAmelCase__ =OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) lowerCAmelCase__ =OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) lowerCAmelCase__ =OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) lowerCAmelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) lowerCAmelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) lowerCAmelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) lowerCAmelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) lowerCAmelCase__ =_LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) lowerCAmelCase__ =_LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_MAPPING lowerCAmelCase__ =auto_class_update(FlaxAutoModel) class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING lowerCAmelCase__ =auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING lowerCAmelCase__ =auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING lowerCAmelCase__ =auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowerCAmelCase__ =auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowerCAmelCase__ =auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING lowerCAmelCase__ =auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowerCAmelCase__ =auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING lowerCAmelCase__ =auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING lowerCAmelCase__ =auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING lowerCAmelCase__ =auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING lowerCAmelCase__ =auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class A__( _BaseAutoModelClass ): lowerCAmelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING lowerCAmelCase__ =auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
482
1
'''simple docstring''' import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCAmelCase__ ( UpperCAmelCase , UpperCAmelCase ): """simple docstring""" snake_case__ : Any = torch.load(UpperCAmelCase , map_location="""cpu""" ) snake_case__ : List[Any] = chkpt["""model"""] # We have the base model one level deeper than the original XLM repository snake_case__ : List[Any] = {} for k, v in state_dict.items(): if "pred_layer" in k: snake_case__ : Union[str, Any] = v else: snake_case__ : str = v snake_case__ : Optional[int] = chkpt["""params"""] snake_case__ : List[Any] = {n: v for n, v in config.items() if not isinstance(UpperCAmelCase , (torch.FloatTensor, numpy.ndarray) )} snake_case__ : Any = chkpt["""dico_word2id"""] snake_case__ : Optional[int] = {s + """</w>""" if s.find("""@@""" ) == -1 and i > 13 else s.replace("""@@""" , """""" ): i for s, i in vocab.items()} # Save pytorch-model snake_case__ : str = pytorch_dump_folder_path + """/""" + WEIGHTS_NAME snake_case__ : Optional[int] = pytorch_dump_folder_path + """/""" + CONFIG_NAME snake_case__ : str = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""vocab_file"""] print(f"""Save PyTorch model to {pytorch_weights_dump_path}""" ) torch.save(UpperCAmelCase , UpperCAmelCase ) print(f"""Save configuration file to {pytorch_config_dump_path}""" ) with open(UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCAmelCase , indent=2 ) + """\n""" ) print(f"""Save vocab file to {pytorch_config_dump_path}""" ) with open(UpperCAmelCase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(UpperCAmelCase , indent=2 ) + """\n""" ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) lowerCAmelCase__ = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
172
'''simple docstring''' import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow lowerCAmelCase__ = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class _A ( unittest.TestCase ): '''simple docstring''' def __lowerCAmelCase ( self : List[str] , lowerCamelCase : Path , lowerCamelCase : Union[str, None] = None , lowerCamelCase : Union[List[str], None] = None , lowerCamelCase : Union[str, List[str], None] = None , lowerCamelCase : bool = True , )-> Dict: snake_case__ : int = [file for file in os.listdir(lowerCamelCase ) if os.path.isfile(os.path.join(lowerCamelCase , lowerCamelCase ) )] if identifier is not None: snake_case__ : List[Any] = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(lowerCamelCase , lowerCamelCase ): for n_ in n_identifier: snake_case__ : Union[str, Any] = [file for file in files if n_ not in file] else: snake_case__ : Optional[Any] = [file for file in files if n_identifier not in file] snake_case__ : Tuple = ignore_files or [] ignore_files.append("""__init__.py""" ) snake_case__ : int = [file for file in files if file not in ignore_files] for file in files: # Open all files print("""Testing""" , lowerCamelCase ) if only_modules: snake_case__ : Union[str, Any] = file.split(""".""" )[0] try: snake_case__ : Any = getattr(lowerCamelCase , lowerCamelCase ) snake_case__ : Optional[Any] = doctest.DocTestSuite(lowerCamelCase ) snake_case__ : int = unittest.TextTestRunner().run(lowerCamelCase ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: snake_case__ : List[Any] = doctest.testfile(str("""..""" / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def __lowerCAmelCase ( self : Tuple )-> List[str]: snake_case__ : Optional[int] = Path("""src/transformers""" ) snake_case__ : Optional[Any] = """modeling""" snake_case__ : Optional[Any] = [ """modeling_ctrl.py""", """modeling_tf_ctrl.py""", ] self.analyze_directory(lowerCamelCase , identifier=lowerCamelCase , ignore_files=lowerCamelCase ) def __lowerCAmelCase ( self : List[str] )-> Union[str, Any]: snake_case__ : Optional[Any] = Path("""src/transformers""" ) snake_case__ : Any = """tokenization""" self.analyze_directory(lowerCamelCase , identifier=lowerCamelCase ) def __lowerCAmelCase ( self : Dict )-> Dict: snake_case__ : Any = Path("""src/transformers""" ) snake_case__ : List[Any] = """configuration""" self.analyze_directory(lowerCamelCase , identifier=lowerCamelCase ) def __lowerCAmelCase ( self : Dict )-> Tuple: snake_case__ : int = Path("""src/transformers""" ) snake_case__ : int = ["""configuration""", """modeling""", """tokenization"""] self.analyze_directory(lowerCamelCase , n_identifier=lowerCamelCase ) def __lowerCAmelCase ( self : Union[str, Any] )-> Tuple: snake_case__ : List[Any] = Path("""docs/source""" ) snake_case__ : Optional[int] = ["""favicon.ico"""] self.analyze_directory(lowerCamelCase , ignore_files=lowerCamelCase , only_modules=lowerCamelCase )
172
1
"""simple docstring""" import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex _lowerCAmelCase = logging.getLogger(__name__) class UpperCamelCase : def __init__( self :List[Any] ) ->Any: lowercase : List[str] = False def __snake_case ( self :Union[str, Any] , __magic_name__ :List[str] , __magic_name__ :Tuple , __magic_name__ :Optional[Any] , __magic_name__ :str ) ->List[Any]: if not self.initialized: lowercase : Tuple = RagRetriever( __snake_case , question_encoder_tokenizer=__snake_case , generator_tokenizer=__snake_case , index=__snake_case , init_retrieval=__snake_case , ) lowercase : Tuple = True def __snake_case ( self :Dict ) ->Any: self.retriever.index.init_index() def __snake_case ( self :Optional[int] , __magic_name__ :str , __magic_name__ :Any ) ->Optional[int]: lowercase : Optional[int] = self.retriever._main_retrieve(__snake_case , __snake_case ) return doc_ids, retrieved_doc_embeds class UpperCamelCase (__snake_case ): def __init__( self :Optional[int] , __magic_name__ :Any , __magic_name__ :Dict , __magic_name__ :Tuple , __magic_name__ :Any , __magic_name__ :Dict=None ) ->Optional[int]: if index is not None and index.is_initialized() and len(__snake_case ) > 0: raise ValueError( """When using Ray for distributed fine-tuning, """ """you\'ll need to provide the paths instead, """ """as the dataset and the index are loaded """ """separately. More info in examples/rag/use_own_knowledge_dataset.py """ ) super().__init__( __snake_case , question_encoder_tokenizer=__snake_case , generator_tokenizer=__snake_case , index=__snake_case , init_retrieval=__snake_case , ) lowercase : List[Any] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(__snake_case , __snake_case , __snake_case , __snake_case ) for worker in self.retrieval_workers ] ) def __snake_case ( self :Optional[Any] ) ->Optional[Any]: logger.info("""initializing retrieval""" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __snake_case ( self :str , __magic_name__ :Dict , __magic_name__ :List[str] ) ->Optional[int]: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. lowercase : Tuple = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] lowercase : Union[str, Any] = ray.get(random_worker.retrieve.remote(__snake_case , __snake_case ) ) else: lowercase : str = self._main_retrieve(__snake_case , __snake_case ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__snake_case ) @classmethod def __snake_case ( cls :str , __magic_name__ :Any , __magic_name__ :Tuple=None , **__magic_name__ :Optional[int] ) ->List[Any]: return super(__snake_case , cls ).get_tokenizers(__snake_case , __snake_case , **__snake_case ) @classmethod def __snake_case ( cls :Dict , __magic_name__ :Tuple , __magic_name__ :Optional[int] , __magic_name__ :str=None , **__magic_name__ :Optional[int] ) ->Any: lowercase : Tuple = kwargs.pop("""config""" , __snake_case ) or RagConfig.from_pretrained(__snake_case , **__snake_case ) lowercase : Any = RagTokenizer.from_pretrained(__snake_case , config=__snake_case ) lowercase : Union[str, Any] = rag_tokenizer.question_encoder lowercase : Any = rag_tokenizer.generator if indexed_dataset is not None: lowercase : Dict = '''custom''' lowercase : Optional[Any] = CustomHFIndex(config.retrieval_vector_size , __snake_case ) else: lowercase : str = cls._build_index(__snake_case ) return cls( __snake_case , question_encoder_tokenizer=__snake_case , generator_tokenizer=__snake_case , retrieval_workers=__snake_case , index=__snake_case , )
264
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss __UpperCAmelCase : List[Any] = pytest.mark.integration @require_faiss class lowerCamelCase ( SCREAMING_SNAKE_CASE ): def snake_case_ ( self : Tuple ) -> Tuple: _a : Tuple = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(__snake_case ) for x in np.arange(30 ).tolist()]} ) return dset def snake_case_ ( self : Optional[Any] ) -> str: import faiss _a : Dataset = self._create_dummy_dataset() _a : Optional[Any] = dset.map( lambda __snake_case , __snake_case : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=__snake_case , keep_in_memory=__snake_case ) _a : List[Any] = dset.add_faiss_index('''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) _a , _a : Union[str, Any] = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) dset.drop_index('''vecs''' ) def snake_case_ ( self : Optional[Any] ) -> str: import faiss _a : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) _a , _a : int = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def snake_case_ ( self : List[Any] ) -> List[str]: import faiss _a : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__snake_case ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) _a , _a : Dict = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def snake_case_ ( self : Dict ) -> int: _a : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name='''vecs''' ) dset.drop_index('''vecs''' ) self.assertRaises(__snake_case , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def snake_case_ ( self : List[str] ) -> Dict: from elasticsearch import Elasticsearch _a : Dataset = self._create_dummy_dataset() with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: _a : int = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 30 ) _a : Dict = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 29}]}} _a : List[Any] = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=__snake_case ) _a , _a : Any = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class lowerCamelCase ( SCREAMING_SNAKE_CASE ): def snake_case_ ( self : str ) -> Any: import faiss _a : List[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query _a : Union[str, Any] = np.zeros(5 , dtype=np.floataa ) _a : Optional[Any] = 1 _a , _a : Optional[int] = index.search(__snake_case ) self.assertRaises(__snake_case , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries _a : Optional[int] = np.eye(5 , dtype=np.floataa )[::-1] _a , _a : Any = index.search_batch(__snake_case ) self.assertRaises(__snake_case , index.search_batch , queries[0] ) _a : Dict = [scores[0] for scores in total_scores] _a : Tuple = [indices[0] for indices in total_indices] self.assertGreater(np.min(__snake_case ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , __snake_case ) def snake_case_ ( self : List[str] ) -> int: import faiss _a : List[str] = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) _a : Union[str, Any] = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(__snake_case ): _a : Optional[Any] = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def snake_case_ ( self : Union[str, Any] ) -> Union[str, Any]: import faiss _a : Tuple = faiss.IndexFlat(5 ) _a : Optional[Any] = FaissIndex(custom_index=__snake_case ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def snake_case_ ( self : Union[str, Any] ) -> Tuple: import faiss _a : List[str] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=__snake_case ) as tmp_file: index.save(tmp_file.name ) _a : int = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) _a : List[Any] = np.zeros(5 , dtype=np.floataa ) _a : List[Any] = 1 _a , _a : List[str] = index.search(__snake_case ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def lowerCamelCase_ ( UpperCamelCase_ ): import faiss _a : List[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) _a : Optional[int] = '''index.faiss''' _a : List[Any] = f"""mock://{index_name}""" index.save(UpperCamelCase_ , storage_options=mockfs.storage_options ) _a : str = FaissIndex.load(UpperCamelCase_ , storage_options=mockfs.storage_options ) _a : Union[str, Any] = np.zeros(5 , dtype=np.floataa ) _a : Dict = 1 _a , _a : List[Any] = index.search(UpperCamelCase_ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class lowerCamelCase ( SCREAMING_SNAKE_CASE ): def snake_case_ ( self : Any ) -> str: from elasticsearch import Elasticsearch with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: _a : List[Any] = Elasticsearch() _a : int = {'''acknowledged''': True} _a : Tuple = ElasticSearchIndex(es_client=__snake_case ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query _a : Any = '''foo''' _a : Union[str, Any] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} _a , _a : Union[str, Any] = index.search(__snake_case ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout _a : List[str] = '''foo''' _a : Optional[int] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} _a , _a : str = index.search(__snake_case , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries _a : Union[str, Any] = ['''foo''', '''bar''', '''foobar'''] _a : int = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} _a , _a : Any = index.search_batch(__snake_case ) _a : Optional[Any] = [scores[0] for scores in total_scores] _a : List[str] = [indices[0] for indices in total_indices] self.assertGreater(np.min(__snake_case ) , 0 ) self.assertListEqual([1, 1, 1] , __snake_case ) # batched queries with timeout _a : Any = ['''foo''', '''bar''', '''foobar'''] _a : List[str] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} _a , _a : List[str] = index.search_batch(__snake_case , request_timeout=30 ) _a : Optional[Any] = [scores[0] for scores in total_scores] _a : str = [indices[0] for indices in total_indices] self.assertGreater(np.min(__snake_case ) , 0 ) self.assertListEqual([1, 1, 1] , __snake_case )
471
0
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class UpperCamelCase_ ( __UpperCamelCase ): """simple docstring""" A = 42 A = None def UpperCamelCase__ ( _A: Dict , _A: Optional[Any]=0.999 , _A: Union[str, Any]="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(_A: str ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_A: int ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __lowerCamelCase = [] for i in range(_A ): __lowerCamelCase = i / num_diffusion_timesteps __lowerCamelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_A ) / alpha_bar_fn(_A ) , _A ) ) return torch.tensor(_A , dtype=torch.floataa ) class UpperCamelCase_ ( __UpperCamelCase ,__UpperCamelCase ): """simple docstring""" A = 1 @register_to_config def __init__( self , UpperCAmelCase = 1_0_0_0 , UpperCAmelCase = 0.00_01 , UpperCAmelCase = 0.02 , UpperCAmelCase = "linear" , UpperCAmelCase = None , UpperCAmelCase = True , UpperCAmelCase = True , UpperCAmelCase = 0 , UpperCAmelCase = "epsilon" , UpperCAmelCase = 1.0 , **UpperCAmelCase , ): if kwargs.get("""set_alpha_to_one""" , UpperCAmelCase ) is not None: __lowerCamelCase = ( """The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.""" ) deprecate("""set_alpha_to_one""" , """1.0.0""" , UpperCAmelCase , standard_warn=UpperCAmelCase ) __lowerCamelCase = kwargs["""set_alpha_to_one"""] if trained_betas is not None: __lowerCamelCase = torch.tensor(UpperCAmelCase , dtype=torch.floataa ) elif beta_schedule == "linear": __lowerCamelCase = torch.linspace(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __lowerCamelCase = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , UpperCAmelCase , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __lowerCamelCase = betas_for_alpha_bar(UpperCAmelCase ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __lowerCamelCase = 1.0 - self.betas __lowerCamelCase = torch.cumprod(self.alphas , dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. __lowerCamelCase = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution __lowerCamelCase = 1.0 # setable values __lowerCamelCase = None __lowerCamelCase = torch.from_numpy(np.arange(0 , UpperCAmelCase ).copy().astype(np.intaa ) ) def lowerCamelCase_ ( self , UpperCAmelCase , UpperCAmelCase = None ): return sample def lowerCamelCase_ ( self , UpperCAmelCase , UpperCAmelCase = None ): if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:''' f''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle''' f''' maximal {self.config.num_train_timesteps} timesteps.''' ) __lowerCamelCase = num_inference_steps __lowerCamelCase = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 __lowerCamelCase = (np.arange(0 , UpperCAmelCase ) * step_ratio).round().copy().astype(np.intaa ) __lowerCamelCase = torch.from_numpy(UpperCAmelCase ).to(UpperCAmelCase ) self.timesteps += self.config.steps_offset def lowerCamelCase_ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 0.0 , UpperCAmelCase = False , UpperCAmelCase = None , UpperCAmelCase = True , ): # 1. get previous step value (=t+1) __lowerCamelCase = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process __lowerCamelCase = self.alphas_cumprod[timestep] __lowerCamelCase = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) __lowerCamelCase = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": __lowerCamelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 __lowerCamelCase = model_output elif self.config.prediction_type == "sample": __lowerCamelCase = model_output __lowerCamelCase = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": __lowerCamelCase = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output __lowerCamelCase = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or''' """ `v_prediction`""" ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: __lowerCamelCase = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowerCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf __lowerCamelCase = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=UpperCAmelCase , pred_original_sample=UpperCAmelCase ) def __len__( self ): return self.config.num_train_timesteps
712
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function _a : Union[str, Any] = 1.0_54_57_18_17e-34 # unit of ℏ : J * s _a : Optional[Any] = 3e8 # unit of c : m * s^-1 def UpperCamelCase__ ( _A: float , _A: float , _A: float ): '''simple docstring''' if (force, area, distance).count(0 ) != 1: raise ValueError("""One and only one argument must be 0""" ) if force < 0: raise ValueError("""Magnitude of force can not be negative""" ) if distance < 0: raise ValueError("""Distance can not be negative""" ) if area < 0: raise ValueError("""Area can not be negative""" ) if force == 0: __lowerCamelCase = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: __lowerCamelCase = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: __lowerCamelCase = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("""One and only one argument must be 0""" ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
571
0
import json import os from functools import lru_cache from typing import List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a : Dict = logging.get_logger(__name__) a : Union[str, Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all BART models at https://huggingface.co/models?filter=bart a : Optional[int] = { "vocab_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json", }, "merges_file": { "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt", "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt", "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt", "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt", "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt", "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt", }, } a : int = { "facebook/bart-base": 1_024, "facebook/bart-large": 1_024, "facebook/bart-large-mnli": 1_024, "facebook/bart-large-cnn": 1_024, "facebook/bart-large-xsum": 1_024, "yjernite/bart_eli5": 1_024, } @lru_cache() def lowerCamelCase__ ( ): __UpperCAmelCase : List[Any] = ( list(range(ord("""!""" ) , ord("""~""" ) + 1 ) ) + list(range(ord("""¡""" ) , ord("""¬""" ) + 1 ) ) + list(range(ord("""®""" ) , ord("""ÿ""" ) + 1 ) ) ) __UpperCAmelCase : Tuple = bs[:] __UpperCAmelCase : int = 0 for b in range(2**8 ): if b not in bs: bs.append(__lowerCamelCase ) cs.append(2**8 + n ) n += 1 __UpperCAmelCase : Dict = [chr(__lowerCamelCase ) for n in cs] return dict(zip(__lowerCamelCase , __lowerCamelCase ) ) def lowerCamelCase__ ( __lowerCamelCase : int ): __UpperCAmelCase : List[str] = set() __UpperCAmelCase : List[str] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __UpperCAmelCase : str = char return pairs class a ( lowercase__ ): """simple docstring""" a : Any = VOCAB_FILES_NAMES a : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP a : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a : List[str] = ['input_ids', 'attention_mask'] def __init__( self : List[str] , __lowercase : Tuple , __lowercase : List[Any] , __lowercase : Union[str, Any]="replace" , __lowercase : List[Any]="<s>" , __lowercase : List[str]="</s>" , __lowercase : int="</s>" , __lowercase : str="<s>" , __lowercase : Union[str, Any]="<unk>" , __lowercase : Tuple="<pad>" , __lowercase : Tuple="<mask>" , __lowercase : Optional[int]=False , **__lowercase : int , ) -> Any: __UpperCAmelCase : List[Any] = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else bos_token __UpperCAmelCase : Optional[Any] = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else eos_token __UpperCAmelCase : Union[str, Any] = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else sep_token __UpperCAmelCase : List[Any] = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else cls_token __UpperCAmelCase : Dict = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else unk_token __UpperCAmelCase : List[str] = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __UpperCAmelCase : int = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token super().__init__( errors=__lowercase , bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , add_prefix_space=__lowercase , **__lowercase , ) with open(__lowercase , encoding="""utf-8""" ) as vocab_handle: __UpperCAmelCase : str = json.load(__lowercase ) __UpperCAmelCase : Optional[Any] = {v: k for k, v in self.encoder.items()} __UpperCAmelCase : Tuple = errors # how to handle errors in decoding __UpperCAmelCase : Optional[int] = bytes_to_unicode() __UpperCAmelCase : Optional[int] = {v: k for k, v in self.byte_encoder.items()} with open(__lowercase , encoding="""utf-8""" ) as merges_handle: __UpperCAmelCase : Union[str, Any] = merges_handle.read().split("""\n""" )[1:-1] __UpperCAmelCase : List[str] = [tuple(merge.split() ) for merge in bpe_merges] __UpperCAmelCase : List[str] = dict(zip(__lowercase , range(len(__lowercase ) ) ) ) __UpperCAmelCase : Optional[Any] = {} __UpperCAmelCase : Optional[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __UpperCAmelCase : str = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""" ) @property def UpperCAmelCase ( self : Any ) -> List[str]: return len(self.encoder ) def UpperCAmelCase ( self : Dict ) -> int: return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase ( self : Any , __lowercase : Union[str, Any] ) -> Optional[int]: if token in self.cache: return self.cache[token] __UpperCAmelCase : Tuple = tuple(__lowercase ) __UpperCAmelCase : Optional[Any] = get_pairs(__lowercase ) if not pairs: return token while True: __UpperCAmelCase : Tuple = min(__lowercase , key=lambda __lowercase : self.bpe_ranks.get(__lowercase , float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break __UpperCAmelCase , __UpperCAmelCase : List[str] = bigram __UpperCAmelCase : List[str] = [] __UpperCAmelCase : Optional[int] = 0 while i < len(__lowercase ): try: __UpperCAmelCase : List[str] = word.index(__lowercase , __lowercase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __UpperCAmelCase : Tuple = j if word[i] == first and i < len(__lowercase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __UpperCAmelCase : Dict = tuple(__lowercase ) __UpperCAmelCase : Union[str, Any] = new_word if len(__lowercase ) == 1: break else: __UpperCAmelCase : int = get_pairs(__lowercase ) __UpperCAmelCase : Union[str, Any] = """ """.join(__lowercase ) __UpperCAmelCase : int = word return word def UpperCAmelCase ( self : Optional[Any] , __lowercase : int ) -> List[str]: __UpperCAmelCase : List[Any] = [] for token in re.findall(self.pat , __lowercase ): __UpperCAmelCase : Dict = """""".join( self.byte_encoder[b] for b in token.encode("""utf-8""" ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__lowercase ).split(""" """ ) ) return bpe_tokens def UpperCAmelCase ( self : Optional[Any] , __lowercase : Optional[int] ) -> str: return self.encoder.get(__lowercase , self.encoder.get(self.unk_token ) ) def UpperCAmelCase ( self : Any , __lowercase : Any ) -> Optional[Any]: return self.decoder.get(__lowercase ) def UpperCAmelCase ( self : str , __lowercase : Any ) -> List[str]: __UpperCAmelCase : List[Any] = """""".join(__lowercase ) __UpperCAmelCase : str = bytearray([self.byte_decoder[c] for c in text] ).decode("""utf-8""" , errors=self.errors ) return text def UpperCAmelCase ( self : Union[str, Any] , __lowercase : str , __lowercase : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(__lowercase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __UpperCAmelCase : Union[str, Any] = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) __UpperCAmelCase : Optional[int] = os.path.join( __lowercase , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) with open(__lowercase , """w""" , encoding="""utf-8""" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__lowercase , ensure_ascii=__lowercase ) + """\n""" ) __UpperCAmelCase : Tuple = 0 with open(__lowercase , """w""" , encoding="""utf-8""" ) as writer: writer.write("""#version: 0.2\n""" ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __lowercase : kv[1] ): if index != token_index: logger.warning( f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" """ Please check that the tokenizer is not corrupted!""" ) __UpperCAmelCase : Union[str, Any] = token_index writer.write(""" """.join(__lowercase ) + """\n""" ) index += 1 return vocab_file, merge_file def UpperCAmelCase ( self : Optional[int] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __UpperCAmelCase : List[str] = [self.cls_token_id] __UpperCAmelCase : Optional[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase ( self : Dict , __lowercase : List[int] , __lowercase : Optional[List[int]] = None , __lowercase : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowercase , token_ids_a=__lowercase , already_has_special_tokens=__lowercase ) if token_ids_a is None: return [1] + ([0] * len(__lowercase )) + [1] return [1] + ([0] * len(__lowercase )) + [1, 1] + ([0] * len(__lowercase )) + [1] def UpperCAmelCase ( self : int , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ) -> List[int]: __UpperCAmelCase : Optional[int] = [self.sep_token_id] __UpperCAmelCase : List[str] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCAmelCase ( self : List[str] , __lowercase : Optional[Any] , __lowercase : Any=False , **__lowercase : List[str] ) -> Union[str, Any]: __UpperCAmelCase : Optional[int] = kwargs.pop("""add_prefix_space""" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__lowercase ) > 0 and not text[0].isspace()): __UpperCAmelCase : List[Any] = """ """ + text return (text, kwargs)
63
from __future__ import annotations import math def lowerCamelCase__ ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : bool , __lowerCamelCase : list[int] , __lowerCamelCase : float ): if depth < 0: raise ValueError("""Depth cannot be less than 0""" ) if len(__lowerCamelCase ) == 0: raise ValueError("""Scores cannot be empty""" ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1 , node_index * 2 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) , minimax(depth + 1 , node_index * 2 + 1 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) , ) return min( minimax(depth + 1 , node_index * 2 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) , minimax(depth + 1 , node_index * 2 + 1 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) , ) def lowerCamelCase__ ( ): __UpperCAmelCase : Tuple = [90, 23, 6, 33, 21, 65, 123, 34423] __UpperCAmelCase : str = math.log(len(__lowerCamelCase ) , 2 ) print("""Optimal value : """ , end="""""" ) print(minimax(0 , 0 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
63
1
'''simple docstring''' import os import re import shutil import sys import tempfile import unittest import black a__ = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, '''utils''')) import check_copies # noqa: E402 # This is the reference code that will be used in the tests. # If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated. a__ = ''' \""" Output class for the scheduler\'s step function output. Args: prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the denoising loop. pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images): The predicted denoised sample (x_{0}) based on the model output from the current timestep. `pred_original_sample` can be used to preview progress or for guidance. \""" prev_sample: torch.FloatTensor pred_original_sample: Optional[torch.FloatTensor] = None ''' class __magic_name__( unittest.TestCase ): def __lowerCAmelCase( self : Optional[int] ): '''simple docstring''' snake_case__ = tempfile.mkdtemp() os.makedirs(os.path.join(self.diffusers_dir , """schedulers/""" ) ) snake_case__ = self.diffusers_dir shutil.copy( os.path.join(__UpperCamelCase , """src/diffusers/schedulers/scheduling_ddpm.py""" ) , os.path.join(self.diffusers_dir , """schedulers/scheduling_ddpm.py""" ) , ) def __lowerCAmelCase( self : List[Any] ): '''simple docstring''' snake_case__ = """src/diffusers""" shutil.rmtree(self.diffusers_dir ) def __lowerCAmelCase( self : int , __UpperCamelCase : Optional[Any] , __UpperCamelCase : List[str] , __UpperCamelCase : List[Any] , __UpperCamelCase : List[Any]=None ): '''simple docstring''' snake_case__ = comment + f"""\nclass {class_name}(nn.Module):\n""" + class_code if overwrite_result is not None: snake_case__ = comment + f"""\nclass {class_name}(nn.Module):\n""" + overwrite_result snake_case__ = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=1_1_9 ) snake_case__ = black.format_str(__UpperCamelCase , mode=__UpperCamelCase ) snake_case__ = os.path.join(self.diffusers_dir , """new_code.py""" ) with open(__UpperCamelCase , """w""" , newline="""\n""" ) as f: f.write(__UpperCamelCase ) if overwrite_result is None: self.assertTrue(len(check_copies.is_copy_consistent(__UpperCamelCase ) ) == 0 ) else: check_copies.is_copy_consistent(f.name , overwrite=__UpperCamelCase ) with open(__UpperCamelCase , """r""" ) as f: self.assertTrue(f.read() , __UpperCamelCase ) def __lowerCAmelCase( self : List[str] ): '''simple docstring''' snake_case__ = check_copies.find_code_in_diffusers("""schedulers.scheduling_ddpm.DDPMSchedulerOutput""" ) self.assertEqual(__UpperCamelCase , __UpperCamelCase ) def __lowerCAmelCase( self : Tuple ): '''simple docstring''' self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , REFERENCE_CODE + """\n""" , ) # With no empty line at the end self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput""" , """DDPMSchedulerOutput""" , __UpperCamelCase , ) # Copy consistency with rename self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , re.sub("""DDPM""" , """Test""" , __UpperCamelCase ) , ) # Copy consistency with a really long name snake_case__ = """TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason""" self.check_copy_consistency( f"""# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}""" , f"""{long_class_name}SchedulerOutput""" , re.sub("""Bert""" , __UpperCamelCase , __UpperCamelCase ) , ) # Copy consistency with overwrite self.check_copy_consistency( """# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test""" , """TestSchedulerOutput""" , __UpperCamelCase , overwrite_result=re.sub("""DDPM""" , """Test""" , __UpperCamelCase ) , )
704
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny - # all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and # emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files. # The latter is done by `fsmt-make-super-tiny-model.py`. # # It will be used then as "stas/tiny-wmt19-en-ru" from pathlib import Path import json import tempfile from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES a__ = '''tiny-wmt19-en-ru''' # Build # borrowed from a test a__ = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] a__ = dict(zip(vocab, range(len(vocab)))) a__ = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] with tempfile.TemporaryDirectory() as tmpdirname: a__ = Path(tmpdirname) a__ = build_dir / VOCAB_FILES_NAMES['''src_vocab_file'''] a__ = build_dir / VOCAB_FILES_NAMES['''tgt_vocab_file'''] a__ = build_dir / VOCAB_FILES_NAMES['''merges_file'''] with open(src_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(tgt_vocab_file, '''w''') as fp: fp.write(json.dumps(vocab_tokens)) with open(merges_file, '''w''') as fp: fp.write('''\n'''.join(merges)) a__ = FSMTTokenizer( langs=['''en''', '''ru'''], src_vocab_size=len(vocab), tgt_vocab_size=len(vocab), src_vocab_file=src_vocab_file, tgt_vocab_file=tgt_vocab_file, merges_file=merges_file, ) a__ = FSMTConfig( langs=['''ru''', '''en'''], src_vocab_size=1_000, tgt_vocab_size=1_000, d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) a__ = FSMTForConditionalGeneration(config) print(F"num of params {tiny_model.num_parameters()}") # Test a__ = tokenizer(['''Making tiny model'''], return_tensors='''pt''') a__ = tiny_model(**batch) print('''test output:''', len(outputs.logits[0])) # Save tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"Generated {mname_tiny}") # Upload # transformers-cli upload tiny-wmt19-en-ru
566
0
import os from datetime import datetime as dt from github import Github __a :Dict = [ 'good first issue', 'good second issue', 'good difficult issue', 'enhancement', 'new pipeline/model', 'new scheduler', 'wip', ] def __snake_case ( ): """simple docstring""" A_ = Github(os.environ["GITHUB_TOKEN"] ) A_ = g.get_repo("huggingface/diffusers" ) A_ = repo.get_issues(state="open" ) for issue in open_issues: A_ = sorted(issue.get_comments() ,key=lambda __UpperCamelCase : i.created_at ,reverse=__UpperCamelCase ) A_ = comments[0] if len(__UpperCamelCase ) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Closes the issue after 7 days of inactivity since the Stalebot notification. issue.edit(state="closed" ) elif ( "stale" in issue.get_labels() and last_comment is not None and last_comment.user.login != "github-actions[bot]" ): # Opens the issue if someone other than Stalebot commented. issue.edit(state="open" ) issue.remove_from_labels("stale" ) elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Post a Stalebot notification after 23 days of inactivity. issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/diffusers/blob/main/CONTRIBUTING.md) " "are likely to be ignored." ) issue.add_to_labels("stale" ) if __name__ == "__main__": main()
86
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu SCREAMING_SNAKE_CASE__ = False class a_ ( unittest.TestCase ): def A__ ( self ) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def A__ ( self ) -> List[str]: """simple docstring""" return 12 @property def A__ ( self ) -> int: """simple docstring""" return 12 @property def A__ ( self ) -> int: """simple docstring""" return 32 @property def A__ ( self ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def A__ ( self ) -> Any: """simple docstring""" UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def A__ ( self ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(_SCREAMING_SNAKE_CASE ) @property def A__ ( self ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = 12 UpperCamelCase = 12 UpperCamelCase = { """attention_bias""": True, """cross_attention_dim""": 32, """attention_head_dim""": height * width, """num_attention_heads""": 1, """num_vector_embeds""": self.num_embed, """num_embeds_ada_norm""": self.num_embeds_ada_norm, """norm_num_groups""": 32, """sample_size""": width, """activation_fn""": """geglu-approximate""", } UpperCamelCase = TransformeraDModel(**_SCREAMING_SNAKE_CASE ) return model def A__ ( self ) -> List[str]: """simple docstring""" UpperCamelCase = """cpu""" UpperCamelCase = self.dummy_vqvae UpperCamelCase = self.dummy_text_encoder UpperCamelCase = self.dummy_tokenizer UpperCamelCase = self.dummy_transformer UpperCamelCase = VQDiffusionScheduler(self.num_embed ) UpperCamelCase = LearnedClassifierFreeSamplingEmbeddings(learnable=_SCREAMING_SNAKE_CASE ) UpperCamelCase = VQDiffusionPipeline( vqvae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , transformer=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , learned_classifier_free_sampling_embeddings=_SCREAMING_SNAKE_CASE , ) UpperCamelCase = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase = """teddy bear playing in the pool""" UpperCamelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase = pipe([prompt] , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" ) UpperCamelCase = output.images UpperCamelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase = pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , output_type="""np""" , return_dict=_SCREAMING_SNAKE_CASE , num_inference_steps=2 )[0] UpperCamelCase = image[0, -3:, -3:, -1] UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) UpperCamelCase = np.array([0.6_5_5_1, 0.6_1_6_8, 0.5_0_0_8, 0.5_6_7_6, 0.5_6_5_9, 0.4_2_9_5, 0.6_0_7_3, 0.5_5_9_9, 0.4_9_9_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def A__ ( self ) -> Dict: """simple docstring""" UpperCamelCase = """cpu""" UpperCamelCase = self.dummy_vqvae UpperCamelCase = self.dummy_text_encoder UpperCamelCase = self.dummy_tokenizer UpperCamelCase = self.dummy_transformer UpperCamelCase = VQDiffusionScheduler(self.num_embed ) UpperCamelCase = LearnedClassifierFreeSamplingEmbeddings( learnable=_SCREAMING_SNAKE_CASE , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) UpperCamelCase = VQDiffusionPipeline( vqvae=_SCREAMING_SNAKE_CASE , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE , transformer=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , learned_classifier_free_sampling_embeddings=_SCREAMING_SNAKE_CASE , ) UpperCamelCase = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) UpperCamelCase = """teddy bear playing in the pool""" UpperCamelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase = pipe([prompt] , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" ) UpperCamelCase = output.images UpperCamelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase = pipe( [prompt] , generator=_SCREAMING_SNAKE_CASE , output_type="""np""" , return_dict=_SCREAMING_SNAKE_CASE , num_inference_steps=2 )[0] UpperCamelCase = image[0, -3:, -3:, -1] UpperCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 24, 24, 3) UpperCamelCase = np.array([0.6_6_9_3, 0.6_0_7_5, 0.4_9_5_9, 0.5_7_0_1, 0.5_5_8_3, 0.4_3_3_3, 0.6_1_7_1, 0.5_6_8_4, 0.4_9_8_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class a_ ( unittest.TestCase ): def A__ ( self ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A__ ( self ) -> List[Any]: """simple docstring""" UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy""" ) UpperCamelCase = VQDiffusionPipeline.from_pretrained("""microsoft/vq-diffusion-ithq""" ) UpperCamelCase = pipeline.to(_SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though UpperCamelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(0 ) UpperCamelCase = pipeline( """teddy bear playing in the pool""" , num_images_per_prompt=1 , generator=_SCREAMING_SNAKE_CASE , output_type="""np""" , ) UpperCamelCase = output.images[0] assert image.shape == (256, 256, 3) assert np.abs(expected_image - image ).max() < 2.0
301
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool lowercase__ = { '''Acehnese Arabic''': '''ace_Arab''', '''Acehnese Latin''': '''ace_Latn''', '''Mesopotamian Arabic''': '''acm_Arab''', '''Ta\'izzi-Adeni Arabic''': '''acq_Arab''', '''Tunisian Arabic''': '''aeb_Arab''', '''Afrikaans''': '''afr_Latn''', '''South Levantine Arabic''': '''ajp_Arab''', '''Akan''': '''aka_Latn''', '''Amharic''': '''amh_Ethi''', '''North Levantine Arabic''': '''apc_Arab''', '''Modern Standard Arabic''': '''arb_Arab''', '''Modern Standard Arabic Romanized''': '''arb_Latn''', '''Najdi Arabic''': '''ars_Arab''', '''Moroccan Arabic''': '''ary_Arab''', '''Egyptian Arabic''': '''arz_Arab''', '''Assamese''': '''asm_Beng''', '''Asturian''': '''ast_Latn''', '''Awadhi''': '''awa_Deva''', '''Central Aymara''': '''ayr_Latn''', '''South Azerbaijani''': '''azb_Arab''', '''North Azerbaijani''': '''azj_Latn''', '''Bashkir''': '''bak_Cyrl''', '''Bambara''': '''bam_Latn''', '''Balinese''': '''ban_Latn''', '''Belarusian''': '''bel_Cyrl''', '''Bemba''': '''bem_Latn''', '''Bengali''': '''ben_Beng''', '''Bhojpuri''': '''bho_Deva''', '''Banjar Arabic''': '''bjn_Arab''', '''Banjar Latin''': '''bjn_Latn''', '''Standard Tibetan''': '''bod_Tibt''', '''Bosnian''': '''bos_Latn''', '''Buginese''': '''bug_Latn''', '''Bulgarian''': '''bul_Cyrl''', '''Catalan''': '''cat_Latn''', '''Cebuano''': '''ceb_Latn''', '''Czech''': '''ces_Latn''', '''Chokwe''': '''cjk_Latn''', '''Central Kurdish''': '''ckb_Arab''', '''Crimean Tatar''': '''crh_Latn''', '''Welsh''': '''cym_Latn''', '''Danish''': '''dan_Latn''', '''German''': '''deu_Latn''', '''Southwestern Dinka''': '''dik_Latn''', '''Dyula''': '''dyu_Latn''', '''Dzongkha''': '''dzo_Tibt''', '''Greek''': '''ell_Grek''', '''English''': '''eng_Latn''', '''Esperanto''': '''epo_Latn''', '''Estonian''': '''est_Latn''', '''Basque''': '''eus_Latn''', '''Ewe''': '''ewe_Latn''', '''Faroese''': '''fao_Latn''', '''Fijian''': '''fij_Latn''', '''Finnish''': '''fin_Latn''', '''Fon''': '''fon_Latn''', '''French''': '''fra_Latn''', '''Friulian''': '''fur_Latn''', '''Nigerian Fulfulde''': '''fuv_Latn''', '''Scottish Gaelic''': '''gla_Latn''', '''Irish''': '''gle_Latn''', '''Galician''': '''glg_Latn''', '''Guarani''': '''grn_Latn''', '''Gujarati''': '''guj_Gujr''', '''Haitian Creole''': '''hat_Latn''', '''Hausa''': '''hau_Latn''', '''Hebrew''': '''heb_Hebr''', '''Hindi''': '''hin_Deva''', '''Chhattisgarhi''': '''hne_Deva''', '''Croatian''': '''hrv_Latn''', '''Hungarian''': '''hun_Latn''', '''Armenian''': '''hye_Armn''', '''Igbo''': '''ibo_Latn''', '''Ilocano''': '''ilo_Latn''', '''Indonesian''': '''ind_Latn''', '''Icelandic''': '''isl_Latn''', '''Italian''': '''ita_Latn''', '''Javanese''': '''jav_Latn''', '''Japanese''': '''jpn_Jpan''', '''Kabyle''': '''kab_Latn''', '''Jingpho''': '''kac_Latn''', '''Kamba''': '''kam_Latn''', '''Kannada''': '''kan_Knda''', '''Kashmiri Arabic''': '''kas_Arab''', '''Kashmiri Devanagari''': '''kas_Deva''', '''Georgian''': '''kat_Geor''', '''Central Kanuri Arabic''': '''knc_Arab''', '''Central Kanuri Latin''': '''knc_Latn''', '''Kazakh''': '''kaz_Cyrl''', '''Kabiyè''': '''kbp_Latn''', '''Kabuverdianu''': '''kea_Latn''', '''Khmer''': '''khm_Khmr''', '''Kikuyu''': '''kik_Latn''', '''Kinyarwanda''': '''kin_Latn''', '''Kyrgyz''': '''kir_Cyrl''', '''Kimbundu''': '''kmb_Latn''', '''Northern Kurdish''': '''kmr_Latn''', '''Kikongo''': '''kon_Latn''', '''Korean''': '''kor_Hang''', '''Lao''': '''lao_Laoo''', '''Ligurian''': '''lij_Latn''', '''Limburgish''': '''lim_Latn''', '''Lingala''': '''lin_Latn''', '''Lithuanian''': '''lit_Latn''', '''Lombard''': '''lmo_Latn''', '''Latgalian''': '''ltg_Latn''', '''Luxembourgish''': '''ltz_Latn''', '''Luba-Kasai''': '''lua_Latn''', '''Ganda''': '''lug_Latn''', '''Luo''': '''luo_Latn''', '''Mizo''': '''lus_Latn''', '''Standard Latvian''': '''lvs_Latn''', '''Magahi''': '''mag_Deva''', '''Maithili''': '''mai_Deva''', '''Malayalam''': '''mal_Mlym''', '''Marathi''': '''mar_Deva''', '''Minangkabau Arabic ''': '''min_Arab''', '''Minangkabau Latin''': '''min_Latn''', '''Macedonian''': '''mkd_Cyrl''', '''Plateau Malagasy''': '''plt_Latn''', '''Maltese''': '''mlt_Latn''', '''Meitei Bengali''': '''mni_Beng''', '''Halh Mongolian''': '''khk_Cyrl''', '''Mossi''': '''mos_Latn''', '''Maori''': '''mri_Latn''', '''Burmese''': '''mya_Mymr''', '''Dutch''': '''nld_Latn''', '''Norwegian Nynorsk''': '''nno_Latn''', '''Norwegian Bokmål''': '''nob_Latn''', '''Nepali''': '''npi_Deva''', '''Northern Sotho''': '''nso_Latn''', '''Nuer''': '''nus_Latn''', '''Nyanja''': '''nya_Latn''', '''Occitan''': '''oci_Latn''', '''West Central Oromo''': '''gaz_Latn''', '''Odia''': '''ory_Orya''', '''Pangasinan''': '''pag_Latn''', '''Eastern Panjabi''': '''pan_Guru''', '''Papiamento''': '''pap_Latn''', '''Western Persian''': '''pes_Arab''', '''Polish''': '''pol_Latn''', '''Portuguese''': '''por_Latn''', '''Dari''': '''prs_Arab''', '''Southern Pashto''': '''pbt_Arab''', '''Ayacucho Quechua''': '''quy_Latn''', '''Romanian''': '''ron_Latn''', '''Rundi''': '''run_Latn''', '''Russian''': '''rus_Cyrl''', '''Sango''': '''sag_Latn''', '''Sanskrit''': '''san_Deva''', '''Santali''': '''sat_Olck''', '''Sicilian''': '''scn_Latn''', '''Shan''': '''shn_Mymr''', '''Sinhala''': '''sin_Sinh''', '''Slovak''': '''slk_Latn''', '''Slovenian''': '''slv_Latn''', '''Samoan''': '''smo_Latn''', '''Shona''': '''sna_Latn''', '''Sindhi''': '''snd_Arab''', '''Somali''': '''som_Latn''', '''Southern Sotho''': '''sot_Latn''', '''Spanish''': '''spa_Latn''', '''Tosk Albanian''': '''als_Latn''', '''Sardinian''': '''srd_Latn''', '''Serbian''': '''srp_Cyrl''', '''Swati''': '''ssw_Latn''', '''Sundanese''': '''sun_Latn''', '''Swedish''': '''swe_Latn''', '''Swahili''': '''swh_Latn''', '''Silesian''': '''szl_Latn''', '''Tamil''': '''tam_Taml''', '''Tatar''': '''tat_Cyrl''', '''Telugu''': '''tel_Telu''', '''Tajik''': '''tgk_Cyrl''', '''Tagalog''': '''tgl_Latn''', '''Thai''': '''tha_Thai''', '''Tigrinya''': '''tir_Ethi''', '''Tamasheq Latin''': '''taq_Latn''', '''Tamasheq Tifinagh''': '''taq_Tfng''', '''Tok Pisin''': '''tpi_Latn''', '''Tswana''': '''tsn_Latn''', '''Tsonga''': '''tso_Latn''', '''Turkmen''': '''tuk_Latn''', '''Tumbuka''': '''tum_Latn''', '''Turkish''': '''tur_Latn''', '''Twi''': '''twi_Latn''', '''Central Atlas Tamazight''': '''tzm_Tfng''', '''Uyghur''': '''uig_Arab''', '''Ukrainian''': '''ukr_Cyrl''', '''Umbundu''': '''umb_Latn''', '''Urdu''': '''urd_Arab''', '''Northern Uzbek''': '''uzn_Latn''', '''Venetian''': '''vec_Latn''', '''Vietnamese''': '''vie_Latn''', '''Waray''': '''war_Latn''', '''Wolof''': '''wol_Latn''', '''Xhosa''': '''xho_Latn''', '''Eastern Yiddish''': '''ydd_Hebr''', '''Yoruba''': '''yor_Latn''', '''Yue Chinese''': '''yue_Hant''', '''Chinese Simplified''': '''zho_Hans''', '''Chinese Traditional''': '''zho_Hant''', '''Standard Malay''': '''zsm_Latn''', '''Zulu''': '''zul_Latn''', } class UpperCAmelCase_ ( _a ): """simple docstring""" snake_case = """facebook/nllb-200-distilled-600M""" snake_case = ( """This is a tool that translates text from a language to another. It takes three inputs: `text`, which should """ """be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, """ """which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in """ """plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`.""" ) snake_case = """translator""" snake_case = AutoTokenizer snake_case = AutoModelForSeqaSeqLM snake_case = LANGUAGE_CODES snake_case = ["""text""", """text""", """text"""] snake_case = ["""text"""] def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): if src_lang not in self.lang_to_code: raise ValueError(f'''{src_lang} is not a supported language.''' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'''{tgt_lang} is not a supported language.''' ) snake_case_ = self.lang_to_code[src_lang] snake_case_ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( _A , return_tensors="pt" , src_lang=_A , tgt_lang=_A ) def _lowercase ( self , UpperCAmelCase_ ): return self.model.generate(**_A ) def _lowercase ( self , UpperCAmelCase_ ): return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=_A )
714
'''simple docstring''' import os import tempfile import unittest from transformers import DistilBertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" def __init__( self , UpperCAmelCase_ , UpperCAmelCase_=13 , UpperCAmelCase_=7 , UpperCAmelCase_=True , UpperCAmelCase_=True , UpperCAmelCase_=False , UpperCAmelCase_=True , UpperCAmelCase_=99 , UpperCAmelCase_=32 , UpperCAmelCase_=5 , UpperCAmelCase_=4 , UpperCAmelCase_=37 , UpperCAmelCase_="gelu" , UpperCAmelCase_=0.1 , UpperCAmelCase_=0.1 , UpperCAmelCase_=5_12 , UpperCAmelCase_=16 , UpperCAmelCase_=2 , UpperCAmelCase_=0.02 , UpperCAmelCase_=3 , UpperCAmelCase_=4 , UpperCAmelCase_=None , ): snake_case_ = parent snake_case_ = batch_size snake_case_ = seq_length snake_case_ = is_training snake_case_ = use_input_mask snake_case_ = use_token_type_ids snake_case_ = use_labels snake_case_ = vocab_size 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_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = type_sequence_label_size snake_case_ = initializer_range snake_case_ = num_labels snake_case_ = num_choices snake_case_ = scope def _lowercase ( self ): snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) snake_case_ = None if self.use_input_mask: snake_case_ = random_attention_mask([self.batch_size, self.seq_length] ) snake_case_ = None snake_case_ = None snake_case_ = None if self.use_labels: snake_case_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) snake_case_ = ids_tensor([self.batch_size] , self.num_choices ) snake_case_ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self ): return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = DistilBertModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = DistilBertForMaskedLM(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = DistilBertForQuestionAnswering(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , start_positions=UpperCAmelCase_ , end_positions=UpperCAmelCase_ ) 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 _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = self.num_labels snake_case_ = DistilBertForSequenceClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = self.num_labels snake_case_ = DistilBertForTokenClassification(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): snake_case_ = self.num_choices snake_case_ = DistilBertForMultipleChoice(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() snake_case_ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() snake_case_ = model( UpperCAmelCase_ , attention_mask=UpperCAmelCase_ , labels=UpperCAmelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self ): snake_case_ = self.prepare_config_and_inputs() ((snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_) , (snake_case_)) = config_and_inputs snake_case_ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , unittest.TestCase ): """simple docstring""" snake_case = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) snake_case = ( { """feature-extraction""": DistilBertModel, """fill-mask""": DistilBertForMaskedLM, """question-answering""": DistilBertForQuestionAnswering, """text-classification""": DistilBertForSequenceClassification, """token-classification""": DistilBertForTokenClassification, """zero-shot""": DistilBertForSequenceClassification, } if is_torch_available() else {} ) snake_case = True snake_case = True snake_case = True snake_case = True def _lowercase ( self ): snake_case_ = DistilBertModelTester(self ) snake_case_ = ConfigTester(self , config_class=UpperCAmelCase_ , dim=37 ) def _lowercase ( self ): self.config_tester.run_common_tests() def _lowercase ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase_ ) def _lowercase ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase_ ) def _lowercase ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase_ ) def _lowercase ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase_ ) def _lowercase ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase_ ) def _lowercase ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase_ ) @slow def _lowercase ( self ): for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case_ = DistilBertModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) @slow @require_torch_gpu def _lowercase ( self ): snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return snake_case_ = True snake_case_ = model_class(config=UpperCAmelCase_ ) snake_case_ = self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) snake_case_ = torch.jit.trace( UpperCAmelCase_ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase_ , os.path.join(UpperCAmelCase_ , "traced_model.pt" ) ) snake_case_ = torch.jit.load(os.path.join(UpperCAmelCase_ , "traced_model.pt" ) , map_location=UpperCAmelCase_ ) loaded(inputs_dict["input_ids"].to(UpperCAmelCase_ ) , inputs_dict["attention_mask"].to(UpperCAmelCase_ ) ) @require_torch class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def _lowercase ( self ): snake_case_ = DistilBertModel.from_pretrained("distilbert-base-uncased" ) snake_case_ = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) snake_case_ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): snake_case_ = model(UpperCAmelCase_ , attention_mask=UpperCAmelCase_ )[0] snake_case_ = torch.Size((1, 11, 7_68) ) self.assertEqual(output.shape , UpperCAmelCase_ ) snake_case_ = torch.tensor( [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase_ , atol=1e-4 ) )
420
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : int = {"vocab_file": "spm_char.model"} SCREAMING_SNAKE_CASE : Tuple = { "vocab_file": { "microsoft/speecht5_asr": "https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model", "microsoft/speecht5_tts": "https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model", "microsoft/speecht5_vc": "https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model", } } SCREAMING_SNAKE_CASE : Dict = { "microsoft/speecht5_asr": 1024, "microsoft/speecht5_tts": 1024, "microsoft/speecht5_vc": 1024, } class snake_case ( lowercase_ ): """simple docstring""" _a = VOCAB_FILES_NAMES _a = PRETRAINED_VOCAB_FILES_MAP _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = ["""input_ids""", """attention_mask"""] def __init__( self, _lowercase, _lowercase="<s>", _lowercase="</s>", _lowercase="<unk>", _lowercase="<pad>", _lowercase = None, **_lowercase, ) -> None: SCREAMING_SNAKE_CASE_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_lowercase, eos_token=_lowercase, unk_token=_lowercase, pad_token=_lowercase, sp_model_kwargs=self.sp_model_kwargs, **_lowercase, ) SCREAMING_SNAKE_CASE_ = vocab_file SCREAMING_SNAKE_CASE_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowercase ) @property def a__ ( self ) -> List[Any]: return self.sp_model.get_piece_size() def a__ ( self ) -> List[Any]: SCREAMING_SNAKE_CASE_ = {self.convert_ids_to_tokens(_lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> List[Any]: SCREAMING_SNAKE_CASE_ = self.__dict__.copy() SCREAMING_SNAKE_CASE_ = None return state def __setstate__( self, _lowercase ) -> str: SCREAMING_SNAKE_CASE_ = d # for backward compatibility if not hasattr(self, 'sp_model_kwargs' ): SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a__ ( self, _lowercase ) -> List[str]: return self.sp_model.encode(_lowercase, out_type=_lowercase ) def a__ ( self, _lowercase ) -> List[str]: return self.sp_model.piece_to_id(_lowercase ) def a__ ( self, _lowercase ) -> List[Any]: SCREAMING_SNAKE_CASE_ = self.sp_model.IdToPiece(_lowercase ) return token def a__ ( self, _lowercase ) -> List[str]: SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = '' 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(_lowercase ) + token SCREAMING_SNAKE_CASE_ = [] else: current_sub_tokens.append(_lowercase ) out_string += self.sp_model.decode(_lowercase ) return out_string.strip() def a__ ( self, _lowercase, _lowercase=None ) -> List[int]: 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 a__ ( self, _lowercase, _lowercase = None, _lowercase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowercase, token_ids_a=_lowercase, already_has_special_tokens=_lowercase ) SCREAMING_SNAKE_CASE_ = [1] if token_ids_a is None: return ([0] * len(_lowercase )) + suffix_ones return ([0] * len(_lowercase )) + ([0] * len(_lowercase )) + suffix_ones def a__ ( self, _lowercase, _lowercase = None ) -> Tuple[str]: if not os.path.isdir(_lowercase ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return SCREAMING_SNAKE_CASE_ = os.path.join( _lowercase, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, _lowercase ) elif not os.path.isfile(self.vocab_file ): with open(_lowercase, 'wb' ) as fi: SCREAMING_SNAKE_CASE_ = self.sp_model.serialized_model_proto() fi.write(_lowercase ) return (out_vocab_file,)
294
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE : Dict = logging.get_logger() def _UpperCamelCase ( lowerCAmelCase__: int ,lowerCAmelCase__: str ,lowerCAmelCase__: LevitConfig ,lowerCAmelCase__: Path ,lowerCAmelCase__: bool = True ) -> Optional[int]: print(F"""Converting {name}...""" ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": SCREAMING_SNAKE_CASE_ = timm.create_model('levit_128s' ,pretrained=lowerCAmelCase__ ) else: SCREAMING_SNAKE_CASE_ = timm.create_model('levit_128' ,pretrained=lowerCAmelCase__ ) if hidden_sizes == 192: SCREAMING_SNAKE_CASE_ = timm.create_model('levit_192' ,pretrained=lowerCAmelCase__ ) if hidden_sizes == 256: SCREAMING_SNAKE_CASE_ = timm.create_model('levit_256' ,pretrained=lowerCAmelCase__ ) if hidden_sizes == 384: SCREAMING_SNAKE_CASE_ = timm.create_model('levit_384' ,pretrained=lowerCAmelCase__ ) from_model.eval() SCREAMING_SNAKE_CASE_ = LevitForImageClassificationWithTeacher(lowerCAmelCase__ ).eval() SCREAMING_SNAKE_CASE_ = OrderedDict() SCREAMING_SNAKE_CASE_ = from_model.state_dict() SCREAMING_SNAKE_CASE_ = list(from_model.state_dict().keys() ) SCREAMING_SNAKE_CASE_ = list(our_model.state_dict().keys() ) print(len(lowerCAmelCase__ ) ,len(lowerCAmelCase__ ) ) for i in range(len(lowerCAmelCase__ ) ): SCREAMING_SNAKE_CASE_ = weights[og_keys[i]] our_model.load_state_dict(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = torch.randn((2, 3, 224, 224) ) SCREAMING_SNAKE_CASE_ = from_model(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = our_model(lowerCAmelCase__ ).logits assert torch.allclose(lowerCAmelCase__ ,lowerCAmelCase__ ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE_ = name print(lowerCAmelCase__ ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) SCREAMING_SNAKE_CASE_ = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(F"""Pushed {checkpoint_name}""" ) def _UpperCamelCase ( lowerCAmelCase__: Path ,lowerCAmelCase__: str = None ,lowerCAmelCase__: bool = True ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE_ = 1000 SCREAMING_SNAKE_CASE_ = (1, num_labels) SCREAMING_SNAKE_CASE_ = 'huggingface/label-files' SCREAMING_SNAKE_CASE_ = num_labels SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(lowerCAmelCase__ ,lowerCAmelCase__ ,repo_type='dataset' ) ,'r' ) ) SCREAMING_SNAKE_CASE_ = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = idalabel SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = partial(lowerCAmelCase__ ,num_labels=lowerCAmelCase__ ,idalabel=lowerCAmelCase__ ,labelaid=lowerCAmelCase__ ) SCREAMING_SNAKE_CASE_ = { 'levit-128S': 128, 'levit-128': 128, 'levit-192': 192, 'levit-256': 256, 'levit-384': 384, } SCREAMING_SNAKE_CASE_ = { 'levit-128S': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] ,num_attention_heads=[4, 6, 8] ,depths=[2, 3, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), 'levit-128': ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] ,num_attention_heads=[4, 8, 12] ,depths=[4, 4, 4] ,key_dim=[16, 16, 16] ,drop_path_rate=0 ,), 'levit-192': ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] ,num_attention_heads=[3, 5, 6] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), 'levit-256': ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] ,num_attention_heads=[4, 6, 8] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0 ,), 'levit-384': ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] ,num_attention_heads=[6, 9, 12] ,depths=[4, 4, 4] ,key_dim=[32, 32, 32] ,drop_path_rate=0.1 ,), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] ,lowerCAmelCase__ ,names_to_config[model_name] ,lowerCAmelCase__ ,lowerCAmelCase__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help="The name of the model you wish to convert, it must be one of the supported Levit* architecture,", ) parser.add_argument( "--pytorch_dump_folder_path", default="levit-dump-folder/", type=Path, required=False, help="Path to the output PyTorch model directory.", ) parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub") parser.add_argument( "--no-push_to_hub", dest="push_to_hub", action="store_false", help="Do not push model and image processor to the hub", ) SCREAMING_SNAKE_CASE : Optional[Any] = parser.parse_args() SCREAMING_SNAKE_CASE : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
294
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 _SCREAMING_SNAKE_CASE : """simple docstring""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=13 , lowerCamelCase__=10 , lowerCamelCase__=3 , lowerCamelCase__=2 , lowerCamelCase__=2 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=32 , lowerCamelCase__=5 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=10 , lowerCamelCase__=0.02 , lowerCamelCase__="divided_space_time" , lowerCamelCase__=None , ) -> Any: lowercase__ : Union[str, Any] = parent lowercase__ : Tuple = batch_size lowercase__ : List[str] = image_size lowercase__ : Optional[Any] = num_channels lowercase__ : Any = patch_size lowercase__ : Union[str, Any] = num_frames lowercase__ : Tuple = is_training lowercase__ : List[str] = use_labels lowercase__ : Any = hidden_size lowercase__ : Tuple = num_hidden_layers lowercase__ : Optional[int] = num_attention_heads lowercase__ : str = intermediate_size lowercase__ : str = hidden_act lowercase__ : Dict = hidden_dropout_prob lowercase__ : Optional[Any] = attention_probs_dropout_prob lowercase__ : Tuple = attention_type lowercase__ : Optional[Any] = initializer_range lowercase__ : str = scope lowercase__ : int = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowercase__ : Any = (image_size // patch_size) ** 2 lowercase__ : Union[str, Any] = (num_frames) * self.num_patches_per_frame + 1 def UpperCAmelCase__( self ) -> Union[str, Any]: lowercase__ : Optional[Any] = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowercase__ : Tuple = None if self.use_labels: lowercase__ : int = ids_tensor([self.batch_size] , self.num_labels ) lowercase__ : int = self.get_config() return config, pixel_values, labels def UpperCAmelCase__( self ) -> List[Any]: lowercase__ : List[str] = 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 , ) lowercase__ : int = self.num_labels return config def UpperCAmelCase__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> Dict: lowercase__ : Tuple = TimesformerModel(config=A_ ) model.to(A_ ) model.eval() lowercase__ : str = model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> str: lowercase__ : Any = TimesformerForVideoClassification(A_ ) model.to(A_ ) model.eval() lowercase__ : List[Any] = model(A_ ) # verify the logits shape lowercase__ : int = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , A_ ) def UpperCAmelCase__( self ) -> Optional[int]: lowercase__ : str = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ : str = config_and_inputs lowercase__ : Union[str, Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class _SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" _a : Optional[int] = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () _a : Dict = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) _a : Optional[Any] = False _a : int = False _a : Any = False _a : Any = False def UpperCAmelCase__( self ) -> List[str]: lowercase__ : Optional[Any] = TimesformerModelTester(self ) lowercase__ : Any = ConfigTester( self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def UpperCAmelCase__( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=False ) -> Any: lowercase__ : Dict = copy.deepcopy(A_ ) if return_labels: if model_class in get_values(A_ ): lowercase__ : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A_ ) return inputs_dict def UpperCAmelCase__( self ) -> Optional[Any]: self.config_tester.run_common_tests() @unittest.skip(reason="""TimeSformer does not use inputs_embeds""" ) def UpperCAmelCase__( self ) -> str: pass def UpperCAmelCase__( self ) -> Optional[Any]: lowercase__ , lowercase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : List[str] = model_class(A_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A_ , nn.Linear ) ) def UpperCAmelCase__( self ) -> Optional[int]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Union[str, Any] = model_class(A_ ) lowercase__ : List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Tuple = [*signature.parameters.keys()] lowercase__ : str = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , A_ ) def UpperCAmelCase__( self ) -> List[Any]: lowercase__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def UpperCAmelCase__( self ) -> Optional[int]: lowercase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*A_ ) @slow def UpperCAmelCase__( self ) -> Optional[int]: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : int = TimesformerModel.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def UpperCAmelCase__( self ) -> Optional[int]: if not self.has_attentions: pass else: lowercase__ , lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Any = True for model_class in self.all_model_classes: lowercase__ : Optional[Any] = self.model_tester.seq_length lowercase__ : Optional[Any] = self.model_tester.num_frames lowercase__ : Union[str, Any] = True lowercase__ : List[Any] = False lowercase__ : Dict = True lowercase__ : int = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): lowercase__ : int = model(**self._prepare_for_class(A_ , A_ ) ) lowercase__ : List[str] = outputs.attentions self.assertEqual(len(A_ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowercase__ : Dict = True lowercase__ : Optional[Any] = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): lowercase__ : Any = model(**self._prepare_for_class(A_ , A_ ) ) lowercase__ : int = outputs.attentions self.assertEqual(len(A_ ) , 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] , ) lowercase__ : Optional[Any] = len(A_ ) # Check attention is always last and order is fine lowercase__ : str = True lowercase__ : List[str] = True lowercase__ : Any = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): lowercase__ : int = model(**self._prepare_for_class(A_ , A_ ) ) self.assertEqual(out_len + 1 , len(A_ ) ) lowercase__ : List[Any] = outputs.attentions self.assertEqual(len(A_ ) , 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 UpperCAmelCase__( self ) -> Dict: def check_hidden_states_output(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowercase__ : Optional[int] = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): lowercase__ : List[Any] = model(**self._prepare_for_class(A_ , A_ ) ) lowercase__ : str = outputs.hidden_states lowercase__ : Dict = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(A_ ) , A_ ) lowercase__ : Any = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowercase__ , lowercase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : str = True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : Union[str, Any] = True check_hidden_states_output(A_ , A_ , A_ ) def snake_case_ ( ): lowercase__ : str = hf_hub_download( repo_id="""hf-internal-testing/spaghetti-video""" , filename="""eating_spaghetti.npy""" , repo_type="""dataset""" ) lowercase__ : Optional[Any] = np.load(lowerCamelCase__ ) return list(lowerCamelCase__ ) @require_torch @require_vision class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase__( self ) -> List[Any]: 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 UpperCAmelCase__( self ) -> str: lowercase__ : Optional[int] = TimesformerForVideoClassification.from_pretrained("""facebook/timesformer-base-finetuned-k400""" ).to( A_ ) lowercase__ : Dict = self.default_image_processor lowercase__ : Optional[int] = prepare_video() lowercase__ : Tuple = image_processor(video[:8] , return_tensors="""pt""" ).to(A_ ) # forward pass with torch.no_grad(): lowercase__ : Optional[Any] = model(**A_ ) # verify the logits lowercase__ : str = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , A_ ) lowercase__ : List[str] = torch.tensor([-0.3016, -0.7713, -0.4205] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A_ , atol=1E-4 ) )
703
"""simple docstring""" from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class _SCREAMING_SNAKE_CASE : """simple docstring""" _a : int _a : Node | None = None _a : Node | None = None def _lowerCamelCase ( ): lowercase__ : List[str] = Node(1 ) lowercase__ : List[str] = Node(2 ) lowercase__ : Any = Node(3 ) lowercase__ : str = Node(4 ) lowercase__ : List[str] = Node(5 ) return tree def _lowerCamelCase ( lowerCamelCase__ : Node | None ): return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _lowerCamelCase ( lowerCamelCase__ : Node | None ): return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _lowerCamelCase ( lowerCamelCase__ : Node | None ): return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _lowerCamelCase ( lowerCamelCase__ : Node | None ): return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _lowerCamelCase ( lowerCamelCase__ : Node | None ): lowercase__ : list[Any] = [] if root is None: return output lowercase__ : Optional[int] = deque([root] ) while process_queue: lowercase__ : Tuple = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _lowerCamelCase ( lowerCamelCase__ : Node | None , lowerCamelCase__ : int ): lowercase__ : list[Any] = [] def populate_output(lowerCamelCase__ : Node | None , lowerCamelCase__ : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(lowerCamelCase__ , lowerCamelCase__ ) return output def _lowerCamelCase ( lowerCamelCase__ : Node | None , lowerCamelCase__ : int ): lowercase__ : list[Any] = [] def populate_output(lowerCamelCase__ : Node | None , lowerCamelCase__ : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(lowerCamelCase__ , lowerCamelCase__ ) return output def _lowerCamelCase ( lowerCamelCase__ : Node | None ): if root is None: return [] lowercase__ : list[Sequence[Node | None]] = [] lowercase__ : Dict = 0 lowercase__ : Union[str, Any] = height(lowerCamelCase__ ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(lowerCamelCase__ , lowerCamelCase__ ) ) lowercase__ : Union[str, Any] = 1 else: output.append(get_nodes_from_right_to_left(lowerCamelCase__ , lowerCamelCase__ ) ) lowercase__ : Any = 0 return output def _lowerCamelCase ( ): # Main function for testing. lowercase__ : List[Any] = make_tree() print(f'''In-order Traversal: {inorder(lowerCamelCase__ )}''' ) print(f'''Pre-order Traversal: {preorder(lowerCamelCase__ )}''' ) print(f'''Post-order Traversal: {postorder(lowerCamelCase__ )}''' , """\n""" ) print(f'''Height of Tree: {height(lowerCamelCase__ )}''' , """\n""" ) print("""Complete Level Order Traversal: """ ) print(level_order(lowerCamelCase__ ) , """\n""" ) print("""Level-wise order Traversal: """ ) for level in range(1 , height(lowerCamelCase__ ) + 1 ): print(f'''Level {level}:''' , get_nodes_from_left_to_right(lowerCamelCase__ , level=lowerCamelCase__ ) ) print("""\nZigZag order Traversal: """ ) print(zigzag(lowerCamelCase__ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
128
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = BlipImageProcessor() __SCREAMING_SNAKE_CASE = GPTaTokenizer.from_pretrained('hf-internal-testing/tiny-random-GPT2Model' ) __SCREAMING_SNAKE_CASE = BertTokenizerFast.from_pretrained('hf-internal-testing/tiny-random-bert' ) __SCREAMING_SNAKE_CASE = InstructBlipProcessor(_A , _A , _A ) processor.save_pretrained(self.tmpdirname ) def _A ( self , **_A ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **_A ).tokenizer def _A ( self , **_A ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **_A ).image_processor def _A ( self , **_A ): '''simple docstring''' return AutoProcessor.from_pretrained(self.tmpdirname , **_A ).qformer_tokenizer def _A ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs] return image_inputs def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) 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=_A , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _A ) self.assertIsInstance(processor.qformer_tokenizer , _A ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_qformer_tokenizer() __SCREAMING_SNAKE_CASE = InstructBlipProcessor( tokenizer=_A , image_processor=_A , qformer_tokenizer=_A ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(_A , return_tensors='np' ) __SCREAMING_SNAKE_CASE = processor(images=_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 _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_qformer_tokenizer() __SCREAMING_SNAKE_CASE = InstructBlipProcessor( tokenizer=_A , image_processor=_A , qformer_tokenizer=_A ) __SCREAMING_SNAKE_CASE = 'lower newer' __SCREAMING_SNAKE_CASE = processor(text=_A ) __SCREAMING_SNAKE_CASE = tokenizer(_A , return_token_type_ids=_A ) __SCREAMING_SNAKE_CASE = qformer_tokenizer(_A , return_token_type_ids=_A ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor['qformer_' + key] ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_qformer_tokenizer() __SCREAMING_SNAKE_CASE = InstructBlipProcessor( tokenizer=_A , image_processor=_A , qformer_tokenizer=_A ) __SCREAMING_SNAKE_CASE = 'lower newer' __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=_A , images=_A ) self.assertListEqual( list(inputs.keys() ) , ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'] , ) # test if it raises when no input is passed with pytest.raises(_A ): processor() def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_qformer_tokenizer() __SCREAMING_SNAKE_CASE = InstructBlipProcessor( tokenizer=_A , image_processor=_A , qformer_tokenizer=_A ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(_A ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(_A ) self.assertListEqual(_A , _A ) def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_qformer_tokenizer() __SCREAMING_SNAKE_CASE = InstructBlipProcessor( tokenizer=_A , image_processor=_A , qformer_tokenizer=_A ) __SCREAMING_SNAKE_CASE = 'lower newer' __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=_A , images=_A ) self.assertListEqual( list(inputs.keys() ) , ['input_ids', 'attention_mask', 'qformer_input_ids', 'qformer_attention_mask', 'pixel_values'] , )
148
import warnings from contextlib import contextmanager from ....processing_utils import ProcessorMixin class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : Optional[int] = '''MCTCTFeatureExtractor''' UpperCamelCase__ : Union[str, Any] = '''AutoTokenizer''' def __init__( self , _A , _A ): '''simple docstring''' super().__init__(_A , _A ) __SCREAMING_SNAKE_CASE = self.feature_extractor __SCREAMING_SNAKE_CASE = False def __call__( self , *_A , **_A ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*_A , **_A ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) __SCREAMING_SNAKE_CASE = kwargs.pop('raw_speech' ) else: __SCREAMING_SNAKE_CASE = kwargs.pop('audio' , _A ) __SCREAMING_SNAKE_CASE = kwargs.pop('sampling_rate' , _A ) __SCREAMING_SNAKE_CASE = kwargs.pop('text' , _A ) if len(_A ) > 0: __SCREAMING_SNAKE_CASE = args[0] __SCREAMING_SNAKE_CASE = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: __SCREAMING_SNAKE_CASE = self.feature_extractor(_A , *_A , sampling_rate=_A , **_A ) if text is not None: __SCREAMING_SNAKE_CASE = self.tokenizer(_A , **_A ) if text is None: return inputs elif audio is None: return encodings else: __SCREAMING_SNAKE_CASE = encodings['input_ids'] return inputs def _A ( self , *_A , **_A ): '''simple docstring''' return self.tokenizer.batch_decode(*_A , **_A ) def _A ( self , *_A , **_A ): '''simple docstring''' if self._in_target_context_manager: return self.current_processor.pad(*_A , **_A ) __SCREAMING_SNAKE_CASE = kwargs.pop('input_features' , _A ) __SCREAMING_SNAKE_CASE = kwargs.pop('labels' , _A ) if len(_A ) > 0: __SCREAMING_SNAKE_CASE = args[0] __SCREAMING_SNAKE_CASE = args[1:] if input_features is not None: __SCREAMING_SNAKE_CASE = self.feature_extractor.pad(_A , *_A , **_A ) if labels is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.pad(_A , **_A ) if labels is None: return input_features elif input_features is None: return labels else: __SCREAMING_SNAKE_CASE = labels['input_ids'] return input_features def _A ( self , *_A , **_A ): '''simple docstring''' return self.tokenizer.decode(*_A , **_A ) @contextmanager def _A ( self ): '''simple docstring''' warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer yield __SCREAMING_SNAKE_CASE = self.feature_extractor __SCREAMING_SNAKE_CASE = False
148
1
from __future__ import annotations def lowerCamelCase ( _UpperCamelCase : Union[str, Any] ) -> bool: '''simple docstring''' __UpperCAmelCase : Optional[int] = len(SCREAMING_SNAKE_CASE_ ) # We need to create solution object to save path. __UpperCAmelCase : int = [[0 for _ in range(SCREAMING_SNAKE_CASE_ )] for _ in range(SCREAMING_SNAKE_CASE_ )] __UpperCAmelCase : str = run_maze(SCREAMING_SNAKE_CASE_ , 0 , 0 , SCREAMING_SNAKE_CASE_ ) if solved: print("""\n""".join(str(SCREAMING_SNAKE_CASE_ ) for row in solutions ) ) else: print("""No solution exists!""" ) return solved def lowerCamelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[int] ) -> bool: '''simple docstring''' __UpperCAmelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE_ ) # Final check point. if i == j == (size - 1): __UpperCAmelCase : Optional[int] = 1 return True __UpperCAmelCase : List[str] = (not i < 0) and (not j < 0) # Check lower bounds __UpperCAmelCase : Union[str, 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 : Tuple = 1 # check for directions if ( run_maze(SCREAMING_SNAKE_CASE_ , i + 1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or run_maze(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , j + 1 , SCREAMING_SNAKE_CASE_ ) or run_maze(SCREAMING_SNAKE_CASE_ , i - 1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or run_maze(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , j - 1 , SCREAMING_SNAKE_CASE_ ) ): return True __UpperCAmelCase : Union[str, Any] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
700
"""simple docstring""" import string # frequency taken from https://en.wikipedia.org/wiki/Letter_frequency UpperCAmelCase : Tuple = { 'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36, 'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29, 'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10, 'Z': 0.07, } UpperCAmelCase : Dict = 'ETAOINSHRDLCUMWFGYPBVKJXQZ' UpperCAmelCase : List[str] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def lowerCamelCase ( _UpperCamelCase : str ) -> dict[str, int]: '''simple docstring''' __UpperCAmelCase : Optional[int] = {letter: 0 for letter in string.ascii_uppercase} for letter in message.upper(): if letter in LETTERS: letter_count[letter] += 1 return letter_count def lowerCamelCase ( _UpperCamelCase : tuple ) -> str: '''simple docstring''' return x[0] def lowerCamelCase ( _UpperCamelCase : str ) -> str: '''simple docstring''' __UpperCAmelCase : int = get_letter_count(_UpperCamelCase ) __UpperCAmelCase : dict[int, list[str]] = { freq: [] for letter, freq in letter_to_freq.items() } for letter in LETTERS: freq_to_letter[letter_to_freq[letter]].append(_UpperCamelCase ) __UpperCAmelCase : dict[int, str] = {} for freq in freq_to_letter: freq_to_letter[freq].sort(key=ETAOIN.find , reverse=_UpperCamelCase ) __UpperCAmelCase : Any = """""".join(freq_to_letter[freq] ) __UpperCAmelCase : Any = list(freq_to_letter_str.items() ) freq_pairs.sort(key=_UpperCamelCase , reverse=_UpperCamelCase ) __UpperCAmelCase : list[str] = [freq_pair[1] for freq_pair in freq_pairs] return "".join(_UpperCamelCase ) def lowerCamelCase ( _UpperCamelCase : str ) -> int: '''simple docstring''' __UpperCAmelCase : List[str] = get_frequency_order(_UpperCamelCase ) __UpperCAmelCase : Optional[int] = 0 for common_letter in ETAOIN[:6]: if common_letter in freq_order[:6]: match_score += 1 for uncommon_letter in ETAOIN[-6:]: if uncommon_letter in freq_order[-6:]: match_score += 1 return match_score if __name__ == "__main__": import doctest doctest.testmod()
299
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class __lowercase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' a : Union[str, Any] = "deta" a : Tuple = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__(self ,_lowerCamelCase=None ,_lowerCamelCase=900 ,_lowerCamelCase=2048 ,_lowerCamelCase=6 ,_lowerCamelCase=2048 ,_lowerCamelCase=8 ,_lowerCamelCase=6 ,_lowerCamelCase=1024 ,_lowerCamelCase=8 ,_lowerCamelCase=0.0 ,_lowerCamelCase=True ,_lowerCamelCase="relu" ,_lowerCamelCase=256 ,_lowerCamelCase=0.1 ,_lowerCamelCase=0.0 ,_lowerCamelCase=0.0 ,_lowerCamelCase=0.0_2 ,_lowerCamelCase=1.0 ,_lowerCamelCase=True ,_lowerCamelCase=False ,_lowerCamelCase="sine" ,_lowerCamelCase=5 ,_lowerCamelCase=4 ,_lowerCamelCase=4 ,_lowerCamelCase=True ,_lowerCamelCase=300 ,_lowerCamelCase=True ,_lowerCamelCase=True ,_lowerCamelCase=1 ,_lowerCamelCase=5 ,_lowerCamelCase=2 ,_lowerCamelCase=1 ,_lowerCamelCase=1 ,_lowerCamelCase=5 ,_lowerCamelCase=2 ,_lowerCamelCase=0.1 ,_lowerCamelCase=0.2_5 ,**_lowerCamelCase ,) -> Dict: '''simple docstring''' if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) __lowercase = CONFIG_MAPPING["resnet"](out_features=['''stage2''', '''stage3''', '''stage4'''] ) else: if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): __lowercase = backbone_config.pop('''model_type''' ) __lowercase = CONFIG_MAPPING[backbone_model_type] __lowercase = config_class.from_dict(_SCREAMING_SNAKE_CASE ) __lowercase = backbone_config __lowercase = num_queries __lowercase = max_position_embeddings __lowercase = d_model __lowercase = encoder_ffn_dim __lowercase = encoder_layers __lowercase = encoder_attention_heads __lowercase = decoder_ffn_dim __lowercase = decoder_layers __lowercase = decoder_attention_heads __lowercase = dropout __lowercase = attention_dropout __lowercase = activation_dropout __lowercase = activation_function __lowercase = init_std __lowercase = init_xavier_std __lowercase = encoder_layerdrop __lowercase = auxiliary_loss __lowercase = position_embedding_type # deformable attributes __lowercase = num_feature_levels __lowercase = encoder_n_points __lowercase = decoder_n_points __lowercase = two_stage __lowercase = two_stage_num_proposals __lowercase = with_box_refine __lowercase = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('''If two_stage is True, with_box_refine must be True.''' ) # Hungarian matcher __lowercase = class_cost __lowercase = bbox_cost __lowercase = giou_cost # Loss coefficients __lowercase = mask_loss_coefficient __lowercase = dice_loss_coefficient __lowercase = bbox_loss_coefficient __lowercase = giou_loss_coefficient __lowercase = eos_coefficient __lowercase = focal_alpha super().__init__(is_encoder_decoder=_SCREAMING_SNAKE_CASE ,**_SCREAMING_SNAKE_CASE ) @property def _UpperCAmelCase (self ) -> int: '''simple docstring''' return self.encoder_attention_heads @property def _UpperCAmelCase (self ) -> int: '''simple docstring''' return self.d_model def _UpperCAmelCase (self ) -> List[Any]: '''simple docstring''' __lowercase = copy.deepcopy(self.__dict__ ) __lowercase = self.backbone_config.to_dict() __lowercase = self.__class__.model_type return output
502
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def _lowercase ( __snake_case ) -> Dict: __lowerCAmelCase : Optional[int] = torch.exp(__snake_case ) __lowerCAmelCase : int = torch.sum(__snake_case ,dim=1 ) # sum of exp(x_i) __lowerCAmelCase : Optional[Any] = torch.sum(x * exp_x ,dim=1 ) # sum of x_i * exp(x_i) return torch.log(__snake_case ) - B / A class A__ ( nn.Module ): '''simple docstring''' def __init__( self: Any , _SCREAMING_SNAKE_CASE: List[Any]) -> List[str]: """simple docstring""" super().__init__() __lowerCAmelCase : Any = config.output_attentions __lowerCAmelCase : Optional[Any] = config.output_hidden_states __lowerCAmelCase : Tuple = nn.ModuleList([BertLayer(_SCREAMING_SNAKE_CASE) for _ in range(config.num_hidden_layers)]) __lowerCAmelCase : int = nn.ModuleList([BertHighway(_SCREAMING_SNAKE_CASE) for _ in range(config.num_hidden_layers)]) __lowerCAmelCase : List[str] = [-1 for _ in range(config.num_hidden_layers)] def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: List[str]) -> Optional[int]: """simple docstring""" if (type(_SCREAMING_SNAKE_CASE) is float) or (type(_SCREAMING_SNAKE_CASE) is int): for i in range(len(self.early_exit_entropy)): __lowerCAmelCase : List[Any] = x else: __lowerCAmelCase : str = x def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] , _SCREAMING_SNAKE_CASE: Tuple) -> List[str]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name]) def _SCREAMING_SNAKE_CASE ( self: int , _SCREAMING_SNAKE_CASE: List[str] , _SCREAMING_SNAKE_CASE: Tuple=None , _SCREAMING_SNAKE_CASE: List[str]=None , _SCREAMING_SNAKE_CASE: List[Any]=None , _SCREAMING_SNAKE_CASE: Tuple=None , ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : Tuple = () __lowerCAmelCase : Tuple = () __lowerCAmelCase : Optional[Any] = () for i, layer_module in enumerate(self.layer): if self.output_hidden_states: __lowerCAmelCase : Tuple = all_hidden_states + (hidden_states,) __lowerCAmelCase : Any = layer_module( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , head_mask[i] , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : str = layer_outputs[0] if self.output_attentions: __lowerCAmelCase : List[Any] = all_attentions + (layer_outputs[1],) __lowerCAmelCase : Optional[int] = (hidden_states,) if self.output_hidden_states: __lowerCAmelCase : Tuple = current_outputs + (all_hidden_states,) if self.output_attentions: __lowerCAmelCase : List[str] = current_outputs + (all_attentions,) __lowerCAmelCase : List[str] = self.highway[i](_SCREAMING_SNAKE_CASE) # logits, pooled_output if not self.training: __lowerCAmelCase : Union[str, Any] = highway_exit[0] __lowerCAmelCase : Dict = entropy(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy __lowerCAmelCase : Dict = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: __lowerCAmelCase : Any = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(_SCREAMING_SNAKE_CASE , i + 1) else: __lowerCAmelCase : Optional[Any] = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: __lowerCAmelCase : Union[str, Any] = all_hidden_states + (hidden_states,) __lowerCAmelCase : str = (hidden_states,) if self.output_hidden_states: __lowerCAmelCase : Union[str, Any] = outputs + (all_hidden_states,) if self.output_attentions: __lowerCAmelCase : Optional[int] = outputs + (all_attentions,) __lowerCAmelCase : List[str] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( 'The Bert Model transformer with early exiting (DeeBERT). ' , __SCREAMING_SNAKE_CASE , ) class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self: Dict , _SCREAMING_SNAKE_CASE: Tuple) -> Union[str, Any]: """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Tuple = config __lowerCAmelCase : str = BertEmbeddings(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = DeeBertEncoder(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[Any] = BertPooler(_SCREAMING_SNAKE_CASE) self.init_weights() def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> Any: """simple docstring""" self.encoder.init_highway_pooler(self.pooler) def _SCREAMING_SNAKE_CASE ( self: str) -> str: """simple docstring""" return self.embeddings.word_embeddings def _SCREAMING_SNAKE_CASE ( self: Optional[int] , _SCREAMING_SNAKE_CASE: List[Any]) -> List[str]: """simple docstring""" __lowerCAmelCase : Dict = value def _SCREAMING_SNAKE_CASE ( self: List[str] , _SCREAMING_SNAKE_CASE: Tuple) -> Optional[int]: """simple docstring""" for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(_SCREAMING_SNAKE_CASE) @add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any]=None , _SCREAMING_SNAKE_CASE: Optional[int]=None , _SCREAMING_SNAKE_CASE: Optional[int]=None , _SCREAMING_SNAKE_CASE: Optional[Any]=None , _SCREAMING_SNAKE_CASE: Any=None , _SCREAMING_SNAKE_CASE: int=None , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: List[Any]=None , ) -> Dict: """simple docstring""" if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: __lowerCAmelCase : Tuple = input_ids.size() elif inputs_embeds is not None: __lowerCAmelCase : List[str] = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") __lowerCAmelCase : Any = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __lowerCAmelCase : Union[str, Any] = torch.ones(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE) if encoder_attention_mask is None: __lowerCAmelCase : Tuple = torch.ones(_SCREAMING_SNAKE_CASE , device=_SCREAMING_SNAKE_CASE) if token_type_ids is None: __lowerCAmelCase : Union[str, Any] = torch.zeros(_SCREAMING_SNAKE_CASE , dtype=torch.long , device=_SCREAMING_SNAKE_CASE) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __lowerCAmelCase : torch.Tensor = self.get_extended_attention_mask(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: __lowerCAmelCase : Union[str, Any] = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: __lowerCAmelCase : Optional[Any] = encoder_attention_mask[:, None, None, :] __lowerCAmelCase : List[str] = encoder_extended_attention_mask.to( dtype=next(self.parameters()).dtype) # fp16 compatibility __lowerCAmelCase : Union[str, Any] = (1.0 - encoder_extended_attention_mask) * -1_0000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __lowerCAmelCase : Union[str, Any] = self.get_head_mask(_SCREAMING_SNAKE_CASE , self.config.num_hidden_layers) __lowerCAmelCase : Union[str, Any] = self.embeddings( input_ids=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , inputs_embeds=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[Any] = self.encoder( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , encoder_attention_mask=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : List[str] = encoder_outputs[0] __lowerCAmelCase : Union[str, Any] = self.pooler(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Dict = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any] , _SCREAMING_SNAKE_CASE: Dict) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : List[Any] = message __lowerCAmelCase : Union[str, Any] = exit_layer # start from 1! class A__ ( nn.Module ): '''simple docstring''' def __init__( self: Dict , _SCREAMING_SNAKE_CASE: Dict) -> str: """simple docstring""" super().__init__() __lowerCAmelCase : Optional[int] = BertPooler(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = nn.Dropout(config.hidden_dropout_prob) __lowerCAmelCase : Optional[Any] = nn.Linear(config.hidden_size , config.num_labels) def _SCREAMING_SNAKE_CASE ( self: int , _SCREAMING_SNAKE_CASE: str) -> List[str]: """simple docstring""" __lowerCAmelCase : Dict = encoder_outputs[0] __lowerCAmelCase : Union[str, Any] = self.pooler(_SCREAMING_SNAKE_CASE) # "return" pooler_output # BertModel __lowerCAmelCase : str = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification __lowerCAmelCase : Tuple = bmodel_output[1] __lowerCAmelCase : int = self.dropout(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = self.classifier(_SCREAMING_SNAKE_CASE) return logits, pooled_output @add_start_docstrings( 'Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. ' , __SCREAMING_SNAKE_CASE , ) class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> Dict: """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = config.num_labels __lowerCAmelCase : Tuple = config.num_hidden_layers __lowerCAmelCase : Optional[Any] = DeeBertModel(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[Any] = nn.Dropout(config.hidden_dropout_prob) __lowerCAmelCase : Dict = nn.Linear(config.hidden_size , self.config.num_labels) self.init_weights() @add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE) def _SCREAMING_SNAKE_CASE ( self: Dict , _SCREAMING_SNAKE_CASE: List[str]=None , _SCREAMING_SNAKE_CASE: Any=None , _SCREAMING_SNAKE_CASE: Dict=None , _SCREAMING_SNAKE_CASE: Optional[Any]=None , _SCREAMING_SNAKE_CASE: Dict=None , _SCREAMING_SNAKE_CASE: Union[str, Any]=None , _SCREAMING_SNAKE_CASE: List[Any]=None , _SCREAMING_SNAKE_CASE: Optional[Any]=-1 , _SCREAMING_SNAKE_CASE: str=False , ) -> List[Any]: """simple docstring""" __lowerCAmelCase : str = self.num_layers try: __lowerCAmelCase : Optional[int] = self.bert( _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , position_ids=_SCREAMING_SNAKE_CASE , head_mask=_SCREAMING_SNAKE_CASE , inputs_embeds=_SCREAMING_SNAKE_CASE , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits __lowerCAmelCase : Tuple = outputs[1] __lowerCAmelCase : Union[str, Any] = self.dropout(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[str] = self.classifier(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: __lowerCAmelCase : str = e.message __lowerCAmelCase : Optional[Any] = e.exit_layer __lowerCAmelCase : Optional[Any] = outputs[0] if not self.training: __lowerCAmelCase : int = entropy(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : str = [] __lowerCAmelCase : Union[str, Any] = [] if labels is not None: if self.num_labels == 1: # We are doing regression __lowerCAmelCase : Optional[int] = MSELoss() __lowerCAmelCase : List[Any] = loss_fct(logits.view(-1) , labels.view(-1)) else: __lowerCAmelCase : Optional[int] = CrossEntropyLoss() __lowerCAmelCase : Tuple = loss_fct(logits.view(-1 , self.num_labels) , labels.view(-1)) # work with highway exits __lowerCAmelCase : List[str] = [] for highway_exit in outputs[-1]: __lowerCAmelCase : List[Any] = highway_exit[0] if not self.training: highway_logits_all.append(_SCREAMING_SNAKE_CASE) highway_entropy.append(highway_exit[2]) if self.num_labels == 1: # We are doing regression __lowerCAmelCase : Optional[int] = MSELoss() __lowerCAmelCase : str = loss_fct(highway_logits.view(-1) , labels.view(-1)) else: __lowerCAmelCase : int = CrossEntropyLoss() __lowerCAmelCase : Optional[Any] = loss_fct(highway_logits.view(-1 , self.num_labels) , labels.view(-1)) highway_losses.append(_SCREAMING_SNAKE_CASE) if train_highway: __lowerCAmelCase : List[Any] = (sum(highway_losses[:-1]),) + outputs # exclude the final highway, of course else: __lowerCAmelCase : int = (loss,) + outputs if not self.training: __lowerCAmelCase : Any = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: __lowerCAmelCase : Any = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
293
0
"""simple docstring""" from random import randint, random def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = False , SCREAMING_SNAKE_CASE = 5 , ) -> list: """simple docstring""" __snake_case = [[-1] * number_of_cells] # Create a highway without any car __snake_case = 0 __snake_case = max(SCREAMING_SNAKE_CASE , 0 ) while i < number_of_cells: __snake_case = ( randint(0 , SCREAMING_SNAKE_CASE ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" __snake_case = 0 __snake_case = highway_now[car_index + 1 :] for cell in range(len(SCREAMING_SNAKE_CASE ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(SCREAMING_SNAKE_CASE , -1 ) def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> list: """simple docstring""" __snake_case = len(SCREAMING_SNAKE_CASE ) # Beforce calculations, the highway is empty __snake_case = [-1] * number_of_cells for car_index in range(SCREAMING_SNAKE_CASE ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed __snake_case = min(highway_now[car_index] + 1 , SCREAMING_SNAKE_CASE ) # Number of empty cell before the next car __snake_case = get_distance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) - 1 # We can't have the car causing an accident __snake_case = min(next_highway[car_index] , SCREAMING_SNAKE_CASE ) if random() < probability: # Randomly, a driver will slow down __snake_case = max(next_highway[car_index] - 1 , 0 ) return next_highway def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> list: """simple docstring""" __snake_case = len(highway[0] ) for i in range(SCREAMING_SNAKE_CASE ): __snake_case = update(highway[i] , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __snake_case = [-1] * number_of_cells for car_index in range(SCREAMING_SNAKE_CASE ): __snake_case = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) __snake_case = (car_index + speed) % number_of_cells # Commit the change of position __snake_case = speed highway.append(SCREAMING_SNAKE_CASE ) return highway if __name__ == "__main__": import doctest doctest.testmod()
700
"""simple docstring""" import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class __magic_name__ : def __init__( self : Optional[int] , snake_case_ : List[str] , snake_case_ : str=13 , snake_case_ : Optional[int]=7 , snake_case_ : Optional[Any]=True , snake_case_ : Union[str, Any]=True , snake_case_ : Tuple=True , snake_case_ : int=True , snake_case_ : int=99 , snake_case_ : Optional[int]=64 , snake_case_ : Dict=32 , snake_case_ : Dict=5 , snake_case_ : List[str]=4 , snake_case_ : List[Any]=37 , snake_case_ : Optional[Any]="gelu" , snake_case_ : Optional[Any]=0.1 , snake_case_ : List[Any]=0.1 , snake_case_ : Union[str, Any]=512 , snake_case_ : int=16 , snake_case_ : List[str]=2 , snake_case_ : Union[str, Any]=0.02 , snake_case_ : Union[str, Any]=3 , snake_case_ : str=4 , snake_case_ : int=None , ): __snake_case = parent __snake_case = batch_size __snake_case = seq_length __snake_case = is_training __snake_case = use_input_mask __snake_case = use_token_type_ids __snake_case = use_labels __snake_case = vocab_size __snake_case = hidden_size __snake_case = embedding_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 = max_position_embeddings __snake_case = type_vocab_size __snake_case = type_sequence_label_size __snake_case = initializer_range __snake_case = num_labels __snake_case = num_choices __snake_case = scope def lowerCAmelCase ( self : Union[str, Any] ): __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case = None if self.use_input_mask: __snake_case = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case = None if self.use_token_type_ids: __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case = None __snake_case = None __snake_case = None if self.use_labels: __snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case = ids_tensor([self.batch_size] , self.num_choices ) __snake_case = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase ( self : Union[str, Any] ): return MobileBertConfig( 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 , embedding_size=self.embedding_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 lowerCAmelCase ( self : Optional[Any] , snake_case_ : Any , snake_case_ : Optional[Any] , snake_case_ : Tuple , snake_case_ : Any , snake_case_ : str , snake_case_ : Dict , snake_case_ : List[str] ): __snake_case = MobileBertModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() __snake_case = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ ) __snake_case = model(snake_case_ , token_type_ids=snake_case_ ) __snake_case = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCAmelCase ( self : List[str] , snake_case_ : List[Any] , snake_case_ : Any , snake_case_ : Optional[int] , snake_case_ : int , snake_case_ : int , snake_case_ : str , snake_case_ : str ): __snake_case = MobileBertForMaskedLM(config=snake_case_ ) model.to(snake_case_ ) model.eval() __snake_case = 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 lowerCAmelCase ( self : Optional[Any] , snake_case_ : Optional[int] , snake_case_ : Union[str, Any] , snake_case_ : List[str] , snake_case_ : int , snake_case_ : int , snake_case_ : int , snake_case_ : Any ): __snake_case = MobileBertForNextSentencePrediction(config=snake_case_ ) model.to(snake_case_ ) model.eval() __snake_case = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def lowerCAmelCase ( self : Optional[int] , snake_case_ : List[str] , snake_case_ : List[str] , snake_case_ : str , snake_case_ : Optional[Any] , snake_case_ : List[str] , snake_case_ : List[str] , snake_case_ : Dict ): __snake_case = MobileBertForPreTraining(config=snake_case_ ) model.to(snake_case_ ) model.eval() __snake_case = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , next_sentence_label=snake_case_ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def lowerCAmelCase ( self : Any , snake_case_ : List[str] , snake_case_ : int , snake_case_ : Any , snake_case_ : Union[str, Any] , snake_case_ : Dict , snake_case_ : int , snake_case_ : int ): __snake_case = MobileBertForQuestionAnswering(config=snake_case_ ) model.to(snake_case_ ) model.eval() __snake_case = 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 lowerCAmelCase ( self : str , snake_case_ : Tuple , snake_case_ : int , snake_case_ : str , snake_case_ : Dict , snake_case_ : Optional[int] , snake_case_ : str , snake_case_ : List[str] ): __snake_case = self.num_labels __snake_case = MobileBertForSequenceClassification(snake_case_ ) model.to(snake_case_ ) model.eval() __snake_case = 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 lowerCAmelCase ( self : Optional[Any] , snake_case_ : Tuple , snake_case_ : str , snake_case_ : Union[str, Any] , snake_case_ : Tuple , snake_case_ : Optional[int] , snake_case_ : Tuple , snake_case_ : List[Any] ): __snake_case = self.num_labels __snake_case = MobileBertForTokenClassification(config=snake_case_ ) model.to(snake_case_ ) model.eval() __snake_case = 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 lowerCAmelCase ( self : Tuple , snake_case_ : Union[str, Any] , snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : Any , snake_case_ : Any , snake_case_ : Dict , snake_case_ : Union[str, Any] ): __snake_case = self.num_choices __snake_case = MobileBertForMultipleChoice(config=snake_case_ ) model.to(snake_case_ ) model.eval() __snake_case = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case = 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 lowerCAmelCase ( self : List[Any] ): __snake_case = self.prepare_config_and_inputs() ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) = config_and_inputs __snake_case = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __magic_name__ ( lowercase__ , lowercase__ , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Dict = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE : Optional[int] = ( { 'feature-extraction': MobileBertModel, 'fill-mask': MobileBertForMaskedLM, 'question-answering': MobileBertForQuestionAnswering, 'text-classification': MobileBertForSequenceClassification, 'token-classification': MobileBertForTokenClassification, 'zero-shot': MobileBertForSequenceClassification, } if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE : int = True def lowerCAmelCase ( self : List[str] , snake_case_ : List[str] , snake_case_ : str , snake_case_ : str=False ): __snake_case = super()._prepare_for_class(snake_case_ , snake_case_ , return_labels=snake_case_ ) if return_labels: if model_class in get_values(snake_case_ ): __snake_case = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=snake_case_ ) __snake_case = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=snake_case_ ) return inputs_dict def lowerCAmelCase ( self : Optional[Any] ): __snake_case = MobileBertModelTester(self ) __snake_case = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def lowerCAmelCase ( self : List[Any] ): self.config_tester.run_common_tests() def lowerCAmelCase ( self : Tuple ): __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*snake_case_ ) def lowerCAmelCase ( self : Optional[Any] ): __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*snake_case_ ) def lowerCAmelCase ( self : Tuple ): __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*snake_case_ ) def lowerCAmelCase ( self : Any ): __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*snake_case_ ) def lowerCAmelCase ( self : Any ): __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*snake_case_ ) def lowerCAmelCase ( self : List[str] ): __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*snake_case_ ) def lowerCAmelCase ( self : List[Any] ): __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*snake_case_ ) def lowerCAmelCase ( self : str ): __snake_case = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*snake_case_ ) def __UpperCamelCase ( SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" return torch.tensor( SCREAMING_SNAKE_CASE , dtype=torch.long , device=SCREAMING_SNAKE_CASE , ) _SCREAMING_SNAKE_CASE = 1E-3 @require_torch @require_sentencepiece @require_tokenizers class __magic_name__ ( unittest.TestCase ): @slow def lowerCAmelCase ( self : Tuple ): __snake_case = MobileBertModel.from_pretrained("google/mobilebert-uncased" ).to(snake_case_ ) __snake_case = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]] ) with torch.no_grad(): __snake_case = model(snake_case_ )[0] __snake_case = torch.Size((1, 9, 512) ) self.assertEqual(output.shape , snake_case_ ) __snake_case = torch.tensor( [ [ [-2.4_73_65_26e07, 8.2_69_16_56e04, 1.6_52_18_38e05], [-5.7_54_17_04e-01, 3.9_05_60_22e00, 4.4_01_15_07e00], [2.6_04_73_59e00, 1.5_67_76_52e00, -1.7_32_41_88e-01], ] ] , device=snake_case_ , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE __snake_case = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) __snake_case = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
614
0
'''simple docstring''' def snake_case_ (UpperCamelCase : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(UpperCamelCase , (list, tuple) ) or not all( isinstance(UpperCamelCase , UpperCamelCase ) for number in numbers ): raise ValueError('''numbers must be an iterable of integers''' ) _a = _a = _a = numbers[0] for i in range(1 , len(UpperCamelCase ) ): # update the maximum and minimum subarray products _a = numbers[i] if number < 0: _a , _a = min_till_now, max_till_now _a = max(UpperCamelCase , max_till_now * number ) _a = min(UpperCamelCase , min_till_now * number ) # update the maximum product found till now _a = max(UpperCamelCase , UpperCamelCase ) return max_prod
22
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ = logging.get_logger(__name__) def _lowerCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = '''huggingface/label-files''' SCREAMING_SNAKE_CASE_ = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE_ = json.load(open(hf_hub_download(__a, __a, repo_type='''dataset''' ), '''r''' ) ) SCREAMING_SNAKE_CASE_ = {int(__a ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE_ = '''std_conv''' if '''bit''' in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" SCREAMING_SNAKE_CASE_ = BitConfig( conv_layer=__a, num_labels=1_000, idalabel=__a, labelaid=__a, ) return config def _lowerCamelCase ( __a ): if "stem.conv" in name: SCREAMING_SNAKE_CASE_ = name.replace('''stem.conv''', '''bit.embedder.convolution''' ) if "blocks" in name: SCREAMING_SNAKE_CASE_ = name.replace('''blocks''', '''layers''' ) if "head.fc" in name: SCREAMING_SNAKE_CASE_ = name.replace('''head.fc''', '''classifier.1''' ) if name.startswith('''norm''' ): SCREAMING_SNAKE_CASE_ = '''bit.''' + name if "bit" not in name and "classifier" not in name: SCREAMING_SNAKE_CASE_ = '''bit.encoder.''' + name return name def _lowerCamelCase ( ): SCREAMING_SNAKE_CASE_ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE_ = Image.open(requests.get(__a, stream=__a ).raw ) return im @torch.no_grad() def _lowerCamelCase ( __a, __a, __a=False ): SCREAMING_SNAKE_CASE_ = get_config(__a ) # load original model from timm SCREAMING_SNAKE_CASE_ = create_model(__a, pretrained=__a ) timm_model.eval() # load state_dict of original model SCREAMING_SNAKE_CASE_ = timm_model.state_dict() for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ = state_dict.pop(__a ) SCREAMING_SNAKE_CASE_ = val.squeeze() if '''head''' in key else val # load HuggingFace model SCREAMING_SNAKE_CASE_ = BitForImageClassification(__a ) model.eval() model.load_state_dict(__a ) # create image processor SCREAMING_SNAKE_CASE_ = create_transform(**resolve_data_config({}, model=__a ) ) SCREAMING_SNAKE_CASE_ = transform.transforms SCREAMING_SNAKE_CASE_ = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE_ = BitImageProcessor( do_resize=__a, size={'''shortest_edge''': timm_transforms[0].size}, resample=pillow_resamplings[timm_transforms[0].interpolation.value], do_center_crop=__a, crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]}, do_normalize=__a, image_mean=timm_transforms[-1].mean.tolist(), image_std=timm_transforms[-1].std.tolist(), ) SCREAMING_SNAKE_CASE_ = prepare_img() SCREAMING_SNAKE_CASE_ = transform(__a ).unsqueeze(0 ) SCREAMING_SNAKE_CASE_ = processor(__a, return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(__a, __a ) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(__a ) SCREAMING_SNAKE_CASE_ = outputs.logits print('''Logits:''', logits[0, :3] ) print('''Predicted class:''', model.config.idalabel[logits.argmax(-1 ).item()] ) SCREAMING_SNAKE_CASE_ = timm_model(__a ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(__a, outputs.logits, atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(__a ).mkdir(exist_ok=__a ) print(F'Saving model {model_name} and processor to {pytorch_dump_folder_path}' ) model.save_pretrained(__a ) processor.save_pretrained(__a ) if push_to_hub: print(F'Pushing model {model_name} and processor to the hub' ) model.push_to_hub(F'ybelkada/{model_name}' ) processor.push_to_hub(F'ybelkada/{model_name}' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) lowerCAmelCase__ = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
626
0
'''simple docstring''' from math import isclose, sqrt def UpperCAmelCase ( UpperCAmelCase__ : float , UpperCAmelCase__ : float , UpperCAmelCase__ : float): lowerCamelCase : Union[str, Any] = point_y / 4 / point_x lowerCamelCase : List[Any] = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) lowerCamelCase : Tuple = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 lowerCamelCase : Union[str, Any] = outgoing_gradient**2 + 4 lowerCamelCase : str = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) lowerCamelCase : Optional[int] = (point_y - outgoing_gradient * point_x) ** 2 - 1_00 lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) lowerCamelCase : Tuple = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) # two solutions, one of which is our input point lowerCamelCase : Dict = x_minus if isclose(UpperCAmelCase__ , UpperCAmelCase__) else x_plus lowerCamelCase : List[Any] = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def UpperCAmelCase ( UpperCAmelCase__ : float = 1.4 , UpperCAmelCase__ : float = -9.6): lowerCamelCase : int = 0 lowerCamelCase : float = first_x_coord lowerCamelCase : float = first_y_coord lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.0_1 <= point_x <= 0.0_1 and point_y > 0): lowerCamelCase : Optional[int] = next_point(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f"""{solution() = }""")
707
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version A = { '<': operator.lt, '<=': operator.le, '==': operator.eq, '!=': operator.ne, '>=': operator.ge, '>': operator.gt, } def UpperCAmelCase ( UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int]): if got_ver is None or want_ver is None: raise ValueError( F'''Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider''' F''' reinstalling {pkg}.''') if not ops[op](version.parse(UpperCAmelCase__) , version.parse(UpperCAmelCase__)): raise ImportError( F'''{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}''') def UpperCAmelCase ( UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None): lowerCamelCase : List[Any] = F'''\n{hint}''' if hint is not None else '' # non-versioned check if re.match(R'^[\w_\-\d]+$' , UpperCAmelCase__): lowerCamelCase , lowerCamelCase , lowerCamelCase : Optional[Any] = requirement, None, None else: lowerCamelCase : Optional[Any] = re.findall(R'^([^!=<>\s]+)([\s!=<>]{1,2}.+)' , UpperCAmelCase__) if not match: raise ValueError( 'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but' F''' got {requirement}''') lowerCamelCase , lowerCamelCase : Dict = match[0] lowerCamelCase : Dict = want_full.split(',') # there could be multiple requirements lowerCamelCase : Union[str, Any] = {} for w in want_range: lowerCamelCase : int = re.findall(R'^([\s!=<>]{1,2})(.+)' , UpperCAmelCase__) if not match: raise ValueError( 'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,' F''' but got {requirement}''') lowerCamelCase , lowerCamelCase : List[Any] = match[0] lowerCamelCase : Optional[int] = want_ver if op not in ops: raise ValueError(F'''{requirement}: need one of {list(ops.keys())}, but got {op}''') # special case if pkg == "python": lowerCamelCase : Optional[int] = '.'.join([str(UpperCAmelCase__) for x in sys.version_info[:3]]) for op, want_ver in wanted.items(): _compare_versions(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) return # check if any version is installed try: lowerCamelCase : Any = importlib.metadata.version(UpperCAmelCase__) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F'''The \'{requirement}\' distribution was not found and is required by this application. {hint}''') # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__) def UpperCAmelCase ( UpperCAmelCase__ : str): lowerCamelCase : List[str] = 'Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main' return require_version(UpperCAmelCase__ , UpperCAmelCase__)
449
0
"""simple docstring""" from __future__ import annotations from math import pi, sqrt def snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> tuple: if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
103
from __future__ import annotations import math def __magic_name__ ( SCREAMING_SNAKE_CASE ) -> list[int]: if num <= 0: _lowercase : List[str] = F"""{num}: Invalid input, please enter a positive integer.""" raise ValueError(SCREAMING_SNAKE_CASE ) _lowercase : Union[str, Any] = [True] * (num + 1) _lowercase : Union[str, Any] = [] _lowercase : Dict = 2 _lowercase : Union[str, Any] = int(math.sqrt(SCREAMING_SNAKE_CASE ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(SCREAMING_SNAKE_CASE ) # Set multiples of start be False for i in range(start * start , num + 1 , SCREAMING_SNAKE_CASE ): if sieve[i] is True: _lowercase : str = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(SCREAMING_SNAKE_CASE ) return prime if __name__ == "__main__": print(prime_sieve(int(input("Enter a positive integer: ").strip())))
66
0
"""simple docstring""" from __future__ import annotations def _lowercase ( __snake_case ) -> int: for i in range(1 ,len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 ,len(__snake_case ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 ,len(__snake_case ) ): for j in range(1 ,len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] ,matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
719
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor __snake_case : Union[str, Any] = random.Random() def _lowercase ( __snake_case ,__snake_case=1.0 ,__snake_case=None ,__snake_case=None ) -> List[Any]: if rng is None: __lowerCAmelCase : Dict = global_rng __lowerCAmelCase : Tuple = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class A__ ( unittest.TestCase ): '''simple docstring''' def __init__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: List[Any]=7 , _SCREAMING_SNAKE_CASE: int=400 , _SCREAMING_SNAKE_CASE: List[str]=2000 , _SCREAMING_SNAKE_CASE: Optional[Any]=24 , _SCREAMING_SNAKE_CASE: Dict=24 , _SCREAMING_SNAKE_CASE: Optional[int]=0.0 , _SCREAMING_SNAKE_CASE: Any=1_6000 , _SCREAMING_SNAKE_CASE: int=True , _SCREAMING_SNAKE_CASE: Union[str, Any]=True , ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Any = parent __lowerCAmelCase : str = batch_size __lowerCAmelCase : List[str] = min_seq_length __lowerCAmelCase : Any = max_seq_length __lowerCAmelCase : Dict = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __lowerCAmelCase : Union[str, Any] = feature_size __lowerCAmelCase : int = num_mel_bins __lowerCAmelCase : Optional[Any] = padding_value __lowerCAmelCase : List[Any] = sampling_rate __lowerCAmelCase : Dict = return_attention_mask __lowerCAmelCase : int = do_normalize def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[int]: """simple docstring""" return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def _SCREAMING_SNAKE_CASE ( self: Tuple , _SCREAMING_SNAKE_CASE: Tuple=False , _SCREAMING_SNAKE_CASE: int=False) -> Optional[int]: """simple docstring""" def _flatten(_SCREAMING_SNAKE_CASE: Optional[Any]): return list(itertools.chain(*_SCREAMING_SNAKE_CASE)) if equal_length: __lowerCAmelCase : Tuple = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] else: # make sure that inputs increase in size __lowerCAmelCase : List[Any] = [ floats_list((x, self.feature_size)) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff) ] if numpify: __lowerCAmelCase : Any = [np.asarray(_SCREAMING_SNAKE_CASE) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class A__ ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = SpeechaTextFeatureExtractor if is_speech_available() else None def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> Tuple: """simple docstring""" __lowerCAmelCase : Tuple = SpeechaTextFeatureExtractionTester(self) def _SCREAMING_SNAKE_CASE ( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Optional[Any]) -> str: """simple docstring""" self.assertTrue(np.all(np.mean(_SCREAMING_SNAKE_CASE , axis=0) < 1e-3)) self.assertTrue(np.all(np.abs(np.var(_SCREAMING_SNAKE_CASE , axis=0) - 1) < 1e-3)) def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> int: """simple docstring""" __lowerCAmelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) # create three inputs of length 800, 1000, and 1200 __lowerCAmelCase : Tuple = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)] __lowerCAmelCase : Optional[int] = [np.asarray(_SCREAMING_SNAKE_CASE) for speech_input in speech_inputs] # Test feature size __lowerCAmelCase : Optional[int] = feature_extractor(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="np").input_features self.assertTrue(input_features.ndim == 3) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size) # Test not batched input __lowerCAmelCase : Optional[Any] = feature_extractor(speech_inputs[0] , return_tensors="np").input_features __lowerCAmelCase : Any = feature_extractor(np_speech_inputs[0] , return_tensors="np").input_features self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3)) # Test batched __lowerCAmelCase : Tuple = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="np").input_features __lowerCAmelCase : Tuple = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="np").input_features for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3)) # Test 2-D numpy arrays are batched. __lowerCAmelCase : List[str] = [floats_list((1, x))[0] for x in (800, 800, 800)] __lowerCAmelCase : Dict = np.asarray(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[int] = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="np").input_features __lowerCAmelCase : Optional[Any] = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="np").input_features for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3)) def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> List[Any]: """simple docstring""" __lowerCAmelCase : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) __lowerCAmelCase : Tuple = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)] __lowerCAmelCase : Optional[Any] = ["longest", "max_length", "do_not_pad"] __lowerCAmelCase : str = [None, 16, None] for max_length, padding in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): __lowerCAmelCase : str = feature_extractor( _SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Optional[Any] = inputs.input_features __lowerCAmelCase : Optional[Any] = inputs.attention_mask __lowerCAmelCase : Tuple = [np.sum(_SCREAMING_SNAKE_CASE) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]) def _SCREAMING_SNAKE_CASE ( self: Any) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) __lowerCAmelCase : Any = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)] __lowerCAmelCase : Dict = ["longest", "max_length", "do_not_pad"] __lowerCAmelCase : List[Any] = [None, 16, None] for max_length, padding in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): __lowerCAmelCase : List[str] = feature_extractor( _SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , return_tensors="np" , return_attention_mask=_SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[str] = inputs.input_features __lowerCAmelCase : Dict = inputs.attention_mask __lowerCAmelCase : Dict = [np.sum(_SCREAMING_SNAKE_CASE) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]) def _SCREAMING_SNAKE_CASE ( self: str) -> Any: """simple docstring""" __lowerCAmelCase : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) __lowerCAmelCase : str = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)] __lowerCAmelCase : str = feature_extractor( _SCREAMING_SNAKE_CASE , padding="max_length" , max_length=4 , truncation=_SCREAMING_SNAKE_CASE , return_tensors="np" , return_attention_mask=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : List[str] = inputs.input_features __lowerCAmelCase : Dict = inputs.attention_mask __lowerCAmelCase : Any = np.sum(attention_mask == 1 , axis=1) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) self._check_zero_mean_unit_variance(input_features[1]) self._check_zero_mean_unit_variance(input_features[2]) def _SCREAMING_SNAKE_CASE ( self: int) -> List[str]: """simple docstring""" __lowerCAmelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) __lowerCAmelCase : List[Any] = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)] __lowerCAmelCase : Any = feature_extractor( _SCREAMING_SNAKE_CASE , padding="longest" , max_length=4 , truncation=_SCREAMING_SNAKE_CASE , return_tensors="np" , return_attention_mask=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : List[str] = inputs.input_features __lowerCAmelCase : Optional[Any] = inputs.attention_mask __lowerCAmelCase : Optional[Any] = np.sum(attention_mask == 1 , axis=1) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]) self._check_zero_mean_unit_variance(input_features[2]) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 4, 24)) __lowerCAmelCase : List[str] = [floats_list((1, x))[0] for x in range(800 , 1400 , 200)] __lowerCAmelCase : List[str] = feature_extractor( _SCREAMING_SNAKE_CASE , padding="longest" , max_length=16 , truncation=_SCREAMING_SNAKE_CASE , return_tensors="np" , return_attention_mask=_SCREAMING_SNAKE_CASE , ) __lowerCAmelCase : Optional[Any] = inputs.input_features __lowerCAmelCase : Optional[int] = inputs.attention_mask __lowerCAmelCase : str = np.sum(attention_mask == 1 , axis=1) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]) self._check_zero_mean_unit_variance(input_features[2]) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape , (3, 6, 24)) def _SCREAMING_SNAKE_CASE ( self: Any) -> Dict: """simple docstring""" import torch __lowerCAmelCase : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) __lowerCAmelCase : List[str] = np.random.rand(100 , 32).astype(np.floataa) __lowerCAmelCase : List[Any] = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __lowerCAmelCase : Any = feature_extractor.pad([{"input_features": inputs}] , return_tensors="np") self.assertTrue(np_processed.input_features.dtype == np.floataa) __lowerCAmelCase : List[Any] = feature_extractor.pad([{"input_features": inputs}] , return_tensors="pt") self.assertTrue(pt_processed.input_features.dtype == torch.floataa) def _SCREAMING_SNAKE_CASE ( self: str , _SCREAMING_SNAKE_CASE: List[Any]) -> Optional[Any]: """simple docstring""" from datasets import load_dataset __lowerCAmelCase : Any = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation") # automatic decoding with librispeech __lowerCAmelCase : List[Any] = ds.sort("id").select(range(_SCREAMING_SNAKE_CASE))[:num_samples]["audio"] return [x["array"] for x in speech_samples] def _SCREAMING_SNAKE_CASE ( self: List[str]) -> Any: """simple docstring""" __lowerCAmelCase : str = np.array([ -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, ]) # fmt: on __lowerCAmelCase : str = self._load_datasamples(1) __lowerCAmelCase : Any = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) __lowerCAmelCase : List[str] = feature_extractor(_SCREAMING_SNAKE_CASE , return_tensors="pt").input_features self.assertEquals(input_features.shape , (1, 584, 24)) self.assertTrue(np.allclose(input_features[0, 0, :30] , _SCREAMING_SNAKE_CASE , atol=1e-4))
615
0
"""simple docstring""" import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import numpy as np from utils_multiple_choice import MultipleChoiceDataset, Split, processors import transformers from transformers import ( AutoConfig, AutoModelForMultipleChoice, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCAmelCase_ : int = logging.getLogger(__name__) def _lowerCAmelCase(a : Optional[int] , a : Any ) -> List[Any]: return (preds == labels).mean() @dataclass class __UpperCAmelCase : '''simple docstring''' lowercase : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) lowercase : Optional[str] = field( default=_lowerCamelCase, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) lowercase : Optional[str] = field( default=_lowerCamelCase, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) lowercase : Optional[str] = field( default=_lowerCamelCase, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) @dataclass class __UpperCAmelCase : '''simple docstring''' lowercase : str = field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys() )} ) lowercase : str = field(metadata={"help": "Should contain the data files for the task."} ) lowercase : int = field( default=128, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) lowercase : bool = field( default=_lowerCamelCase, metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _lowerCAmelCase() -> Tuple: # 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. _SCREAMING_SNAKE_CASE =HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ''' --overwrite_output_dir to overcome.''' ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO 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 ) try: _SCREAMING_SNAKE_CASE =processors[data_args.task_name]() _SCREAMING_SNAKE_CASE =processor.get_labels() _SCREAMING_SNAKE_CASE =len(a ) except KeyError: raise ValueError('''Task not found: %s''' % (data_args.task_name) ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=a , finetuning_task=data_args.task_name , cache_dir=model_args.cache_dir , ) _SCREAMING_SNAKE_CASE =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 , ) _SCREAMING_SNAKE_CASE =AutoModelForMultipleChoice.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 _SCREAMING_SNAKE_CASE =( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=a , task=data_args.task_name , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) _SCREAMING_SNAKE_CASE =( MultipleChoiceDataset( data_dir=data_args.data_dir , tokenizer=a , task=data_args.task_name , 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 compute_metrics(a : EvalPrediction ) -> Dict: _SCREAMING_SNAKE_CASE =np.argmax(p.predictions , axis=1 ) return {"acc": simple_accuracy(a , p.label_ids )} # Data collator _SCREAMING_SNAKE_CASE =DataCollatorWithPadding(a , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer _SCREAMING_SNAKE_CASE =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_master(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _SCREAMING_SNAKE_CASE ={} if training_args.do_eval: logger.info('''*** Evaluate ***''' ) _SCREAMING_SNAKE_CASE =trainer.evaluate() _SCREAMING_SNAKE_CASE =os.path.join(training_args.output_dir , '''eval_results.txt''' ) if trainer.is_world_master(): 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 ) return results def _lowerCAmelCase(a : List[str] ) -> Union[str, Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
255
"""simple docstring""" from __future__ import annotations import numpy as np def _lowerCAmelCase(a : list[float] ) -> Any: return np.maximum(0 , a ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
255
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 SCREAMING_SNAKE_CASE ( a_ : List[Any]=None , a_ : Optional[int]=None ): return field(default_factory=lambda: default , metadata=a_ ) @dataclass class __lowercase : _a = 42 _a = 42 _a = 42 _a = 42 @dataclass class __lowercase : _a = 42 _a = field(default="""toto""" , metadata={"""help""": """help message"""} ) @dataclass class __lowercase : _a = False _a = True _a = None class __lowercase ( __magic_name__ ): _a = """titi""" _a = """toto""" class __lowercase ( __magic_name__ ): _a = """titi""" _a = """toto""" _a = 42 @dataclass class __lowercase : _a = "toto" def UpperCamelCase__ ( self ) -> Any: __a = BasicEnum(self.foo ) @dataclass class __lowercase : _a = "toto" def UpperCamelCase__ ( self ) -> Union[str, Any]: __a = MixedTypeEnum(self.foo ) @dataclass class __lowercase : _a = None _a = field(default=__magic_name__ , metadata={"""help""": """help message"""} ) _a = None _a = list_field(default=[] ) _a = list_field(default=[] ) @dataclass class __lowercase : _a = list_field(default=[] ) _a = list_field(default=[1, 2, 3] ) _a = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] ) _a = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class __lowercase : _a = field() _a = field() _a = field() def UpperCamelCase__ ( self ) -> Tuple: __a = BasicEnum(self.required_enum ) @dataclass class __lowercase : _a = 42 _a = field() _a = None _a = field(default="""toto""" , metadata={"""help""": """help message"""} ) _a = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] ) if is_python_no_less_than_3_10: @dataclass class __lowercase : _a = False _a = True _a = None @dataclass class __lowercase : _a = None _a = field(default=__magic_name__ , metadata={"""help""": """help message"""} ) _a = None _a = list_field(default=[] ) _a = list_field(default=[] ) class __lowercase ( unittest.TestCase ): def UpperCamelCase__ ( self , UpperCamelCase , UpperCamelCase ) -> Any: 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 UpperCamelCase__ ( self ) -> Tuple: __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 UpperCamelCase__ ( self ) -> Optional[int]: __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 UpperCamelCase__ ( self ) -> List[Any]: __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 UpperCamelCase__ ( self ) -> List[Any]: __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 UpperCamelCase__ ( self ) -> Optional[int]: @dataclass class __lowercase : _a = "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 UpperCamelCase__ ( self ) -> Optional[Any]: __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 UpperCamelCase__ ( self ) -> Union[str, Any]: __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 UpperCamelCase__ ( self ) -> Dict: __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 UpperCamelCase__ ( self ) -> Optional[Any]: __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 UpperCamelCase__ ( self ) -> Any: __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 UpperCamelCase__ ( self ) -> Any: __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 UpperCamelCase__ ( self ) -> Any: __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 UpperCamelCase__ ( self ) -> Any: __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 UpperCamelCase__ ( self ) -> Optional[Any]: __a = HfArgumentParser(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase )
490
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
490
1
"""simple docstring""" import random import unittest import torch from diffusers import IFInpaintingPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __magic_name__ ( lowercase__ , lowercase__ , unittest.TestCase ): _SCREAMING_SNAKE_CASE : Optional[int] = IFInpaintingPipeline _SCREAMING_SNAKE_CASE : int = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'} _SCREAMING_SNAKE_CASE : Dict = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _SCREAMING_SNAKE_CASE : Union[str, Any] = PipelineTesterMixin.required_optional_params - {'latents'} def lowerCAmelCase ( self : Tuple ): return self._get_dummy_components() def lowerCAmelCase ( self : List[str] , snake_case_ : Tuple , snake_case_ : Optional[Any]=0 ): if str(snake_case_ ).startswith("mps" ): __snake_case = torch.manual_seed(snake_case_ ) else: __snake_case = torch.Generator(device=snake_case_ ).manual_seed(snake_case_ ) __snake_case = floats_tensor((1, 3, 32, 32) , rng=random.Random(snake_case_ ) ).to(snake_case_ ) __snake_case = floats_tensor((1, 3, 32, 32) , rng=random.Random(snake_case_ ) ).to(snake_case_ ) __snake_case = { "prompt": "A painting of a squirrel eating a burger", "image": image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowerCAmelCase ( self : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) def lowerCAmelCase ( self : Optional[Any] ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowerCAmelCase ( self : List[str] ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1e-1 ) def lowerCAmelCase ( self : str ): self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def lowerCAmelCase ( self : Tuple ): self._test_save_load_local() def lowerCAmelCase ( self : List[Any] ): self._test_inference_batch_single_identical( expected_max_diff=1e-2 , )
163
"""simple docstring""" def __UpperCamelCase ( SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" __snake_case = "" 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 __UpperCamelCase ( SCREAMING_SNAKE_CASE ) -> dict[str, str]: """simple docstring""" __snake_case = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key __snake_case = remove_duplicates(key.upper() ) __snake_case = len(SCREAMING_SNAKE_CASE ) # First fill cipher with key characters __snake_case = {alphabet[i]: char for i, char in enumerate(SCREAMING_SNAKE_CASE )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(SCREAMING_SNAKE_CASE ) , 26 ): __snake_case = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 __snake_case = alphabet[i - offset] __snake_case = char return cipher_alphabet def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return "".join(cipher_map.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for ch in message.upper() ) def __UpperCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" __snake_case = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) for ch in message.upper() ) def __UpperCamelCase ( ) -> None: """simple docstring""" __snake_case = input("Enter message to encode or decode: " ).strip() __snake_case = input("Enter keyword: " ).strip() __snake_case = input("Encipher or decipher? E/D:" ).strip()[0].lower() try: __snake_case = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option" ) __snake_case = create_cipher_map(SCREAMING_SNAKE_CASE ) print(func(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
163
1
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class A__ ( unittest.TestCase ): @slow def lowercase ( self ) -> Optional[int]: """simple docstring""" __magic_name__ : int = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) __magic_name__ : List[str] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) __magic_name__ : str = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids __magic_name__ : Dict = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids __magic_name__ : Optional[Any] = shift_tokens_right(__lowerCAmelCase , model.config.pad_token_id , model.config.decoder_start_token_id ) __magic_name__ : Dict = model(__lowerCAmelCase , decoder_input_ids=__lowerCAmelCase ).logits __magic_name__ : Union[str, Any] = optax.softmax_cross_entropy(__lowerCAmelCase , onehot(__lowerCAmelCase , logits.shape[-1] ) ).mean() __magic_name__ : int = -(labels.shape[-1] * loss.item()) __magic_name__ : int = -8_4.9_1_2_7 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
707
import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate lowercase_ = trt.Logger(trt.Logger.WARNING) lowercase_ = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) lowercase_ = logging.getLogger(__name__) lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=384, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=128, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) lowercase_ = parser.parse_args() if args.tokenizer_name: lowercase_ = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) lowercase_ = args.per_device_eval_batch_size lowercase_ = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties lowercase_ = True lowercase_ = '''temp_engine/bert-fp32.engine''' if args.fpaa: lowercase_ = '''temp_engine/bert-fp16.engine''' if args.inta: lowercase_ = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') lowercase_ = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network lowercase_ = [network.get_input(i) for i in range(network.num_inputs)] lowercase_ = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: lowercase_ = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) lowercase_ = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) lowercase_ = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase ( UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase ) ->Optional[Any]: """simple docstring""" __magic_name__ : Union[str, Any] = np.asarray(inputs['''input_ids'''], dtype=np.intaa ) __magic_name__ : Optional[int] = np.asarray(inputs['''attention_mask'''], dtype=np.intaa ) __magic_name__ : Tuple = np.asarray(inputs['''token_type_ids'''], dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0], input_ids.ravel(), UpperCAmelCase ) cuda.memcpy_htod_async(d_inputs[1], attention_mask.ravel(), UpperCAmelCase ) cuda.memcpy_htod_async(d_inputs[2], token_type_ids.ravel(), UpperCAmelCase ) # start time __magic_name__ : Optional[int] = time.time() # Run inference context.execute_async( bindings=[int(UpperCAmelCase ) for d_inp in d_inputs] + [int(UpperCAmelCase ), int(UpperCAmelCase )], stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(UpperCAmelCase, UpperCAmelCase, UpperCAmelCase ) cuda.memcpy_dtoh_async(UpperCAmelCase, UpperCAmelCase, UpperCAmelCase ) # Synchronize the stream and take time stream.synchronize() # end time __magic_name__ : str = time.time() __magic_name__ : Any = end_time - start_time __magic_name__ : Tuple = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. lowercase_ = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. lowercase_ = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. lowercase_ = raw_datasets['''validation'''].column_names lowercase_ = '''question''' if '''question''' in column_names else column_names[0] lowercase_ = '''context''' if '''context''' in column_names else column_names[1] lowercase_ = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). lowercase_ = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f"The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the" f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." ) lowercase_ = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase ( UpperCAmelCase ) ->int: """simple docstring""" __magic_name__ : Optional[int] = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __magic_name__ : List[str] = tokenizer( examples[question_column_name if pad_on_right else context_column_name], examples[context_column_name if pad_on_right else question_column_name], truncation='''only_second''' if pad_on_right else '''only_first''', max_length=UpperCAmelCase, stride=args.doc_stride, return_overflowing_tokens=UpperCAmelCase, return_offsets_mapping=UpperCAmelCase, padding='''max_length''', ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __magic_name__ : str = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __magic_name__ : str = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __magic_name__ : Dict = tokenized_examples.sequence_ids(UpperCAmelCase ) __magic_name__ : Optional[int] = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __magic_name__ : int = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __magic_name__ : List[Any] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples lowercase_ = raw_datasets['''validation'''] # Validation Feature Creation lowercase_ = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) lowercase_ = default_data_collator lowercase_ = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) lowercase_ = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase ( UpperCAmelCase, UpperCAmelCase, UpperCAmelCase, UpperCAmelCase="eval" ) ->List[str]: """simple docstring""" __magic_name__ : List[str] = postprocess_qa_predictions( examples=UpperCAmelCase, features=UpperCAmelCase, predictions=UpperCAmelCase, version_2_with_negative=args.version_2_with_negative, n_best_size=args.n_best_size, max_answer_length=args.max_answer_length, null_score_diff_threshold=args.null_score_diff_threshold, output_dir=args.output_dir, prefix=UpperCAmelCase, ) # Format the result to the format the metric expects. if args.version_2_with_negative: __magic_name__ : str = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __magic_name__ : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __magic_name__ : Optional[int] = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=UpperCAmelCase, label_ids=UpperCAmelCase ) lowercase_ = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase ( UpperCAmelCase ) ->Optional[Any]: """simple docstring""" return trt.volume(engine.get_binding_shape(UpperCAmelCase ) ) * engine.get_binding_dtype(UpperCAmelCase ).itemsize # Allocate device memory for inputs and outputs. lowercase_ = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer lowercase_ = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) lowercase_ = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) lowercase_ = cuda.mem_alloc(h_outputa.nbytes) lowercase_ = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. lowercase_ = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f" Num examples = {len(eval_dataset)}") logger.info(f" Batch size = {args.per_device_eval_batch_size}") lowercase_ = 0.0 lowercase_ = 0 lowercase_ = timeit.default_timer() lowercase_ = None for step, batch in enumerate(eval_dataloader): lowercase_, lowercase_ = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 lowercase_, lowercase_ = outputs lowercase_ = torch.tensor(start_logits) lowercase_ = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered lowercase_ = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-100) lowercase_ = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-100) lowercase_ = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) lowercase_ = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100) if all_preds is not None: lowercase_ = nested_truncate(all_preds, len(eval_dataset)) lowercase_ = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 1000 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 1000)) logger.info('''Total Number of Inference = %d''', niter) lowercase_ = post_processing_function(eval_examples, eval_dataset, all_preds) lowercase_ = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f"Evaluation metrics: {eval_metric}")
336
0
import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _a ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self ) -> Optional[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def _UpperCAmelCase ( self ) -> int: torch.manual_seed(0 ) UpperCamelCase_ = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def _UpperCAmelCase ( self ) -> str: torch.manual_seed(0 ) UpperCamelCase_ = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def _UpperCAmelCase ( self ) -> Dict: torch.manual_seed(0 ) UpperCamelCase_ = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) UpperCamelCase_ = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def _UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase_ = 'cpu' # ensure determinism for the device-dependent torch.Generator UpperCamelCase_ = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) UpperCamelCase_ = DDPMScheduler() UpperCamelCase_ = AudioDiffusionPipeline(vqvae=_UpperCAmelCase , unet=self.dummy_unet , mel=_UpperCAmelCase , scheduler=_UpperCAmelCase ) UpperCamelCase_ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) UpperCamelCase_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(42 ) UpperCamelCase_ = pipe(generator=_UpperCAmelCase , steps=4 ) UpperCamelCase_ = output.audios[0] UpperCamelCase_ = output.images[0] UpperCamelCase_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(42 ) UpperCamelCase_ = pipe(generator=_UpperCAmelCase , steps=4 , return_dict=_UpperCAmelCase ) UpperCamelCase_ = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) UpperCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] UpperCamelCase_ = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] UpperCamelCase_ = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 UpperCamelCase_ = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) UpperCamelCase_ = DDIMScheduler() UpperCamelCase_ = self.dummy_vqvae_and_unet UpperCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=_UpperCAmelCase , scheduler=_UpperCAmelCase ) UpperCamelCase_ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) np.random.seed(0 ) UpperCamelCase_ = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) UpperCamelCase_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(42 ) UpperCamelCase_ = pipe(raw_audio=_UpperCAmelCase , generator=_UpperCAmelCase , start_step=5 , steps=10 ) UpperCamelCase_ = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) UpperCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] UpperCamelCase_ = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 UpperCamelCase_ = self.dummy_unet_condition UpperCamelCase_ = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=_UpperCAmelCase , mel=_UpperCAmelCase , scheduler=_UpperCAmelCase ) UpperCamelCase_ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) np.random.seed(0 ) UpperCamelCase_ = torch.rand((1, 1, 10) ) UpperCamelCase_ = pipe(generator=_UpperCAmelCase , encoding=_UpperCAmelCase ) UpperCamelCase_ = output.images[0] UpperCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] UpperCamelCase_ = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class _a ( unittest.TestCase ): """simple docstring""" def _UpperCAmelCase ( self ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _UpperCAmelCase ( self ) -> List[str]: UpperCamelCase_ = torch_device UpperCamelCase_ = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) UpperCamelCase_ = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) UpperCamelCase_ = torch.Generator(device=_UpperCAmelCase ).manual_seed(42 ) UpperCamelCase_ = pipe(generator=_UpperCAmelCase ) UpperCamelCase_ = output.audios[0] UpperCamelCase_ = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] UpperCamelCase_ = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] UpperCamelCase_ = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
23
"""simple docstring""" import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def __lowercase ( ): with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(_a ): requests.request('''GET''' , '''https://huggingface.co''' ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request('''GET''' , '''https://huggingface.co''' , timeout=1.0 ) @pytest.mark.integration def __lowercase ( ): with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request('''GET''' , '''https://huggingface.co''' ) def __lowercase ( ): with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(_a ): http_head('''https://huggingface.co''' )
123
0
'''simple docstring''' import platform from argparse import ArgumentParser import huggingface_hub from .. import __version__ as version from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available from . import BaseDiffusersCLICommand def A ( A_ : int ): return EnvironmentCommand() class a ( __magic_name__ ): @staticmethod def __snake_case ( SCREAMING_SNAKE_CASE_ : ArgumentParser ): snake_case : Optional[int] = parser.add_parser('''env''' ) download_parser.set_defaults(func=SCREAMING_SNAKE_CASE_ ) def __snake_case ( self : List[str] ): snake_case : Tuple = huggingface_hub.__version__ snake_case : List[Any] = '''not installed''' snake_case : Optional[Any] = '''NA''' if is_torch_available(): import torch snake_case : str = torch.__version__ snake_case : Any = torch.cuda.is_available() snake_case : Tuple = '''not installed''' if is_transformers_available(): import transformers snake_case : Dict = transformers.__version__ snake_case : Optional[Any] = '''not installed''' if is_accelerate_available(): import accelerate snake_case : List[Any] = accelerate.__version__ snake_case : Optional[int] = '''not installed''' if is_xformers_available(): import xformers snake_case : List[Any] = xformers.__version__ snake_case : str = { '''`diffusers` version''': version, '''Platform''': platform.platform(), '''Python version''': platform.python_version(), '''PyTorch version (GPU?)''': F"""{pt_version} ({pt_cuda_available})""", '''Huggingface_hub version''': hub_version, '''Transformers version''': transformers_version, '''Accelerate version''': accelerate_version, '''xFormers version''': xformers_version, '''Using GPU in script?''': '''<fill in>''', '''Using distributed or parallel set-up in script?''': '''<fill in>''', } print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' ) print(self.format_dict(SCREAMING_SNAKE_CASE_ ) ) return info @staticmethod def __snake_case ( SCREAMING_SNAKE_CASE_ : str ): return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
712
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase = { "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 = ["ConvBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase = [ "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 = [ "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 = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
555
0
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def __lowercase ( snake_case, snake_case ): """simple docstring""" if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __magic_name__ :Optional[Any] = flax_key_tuple[:-1] + ('''weight''',) __magic_name__ :Tuple = torch.permute(snake_case, (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(snake_case ): # linear layer __magic_name__ :Dict = flax_key_tuple[:-1] + ('''weight''',) __magic_name__ :Union[str, Any] = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __magic_name__ :List[str] = flax_key_tuple[:-1] + ('''weight''',) return flax_key_tuple, flax_tensor def __lowercase ( snake_case, snake_case, snake_case ): """simple docstring""" if "metadata" in layer: __magic_name__ :List[str] = layer.split('''metadata''' ) __magic_name__ :int = ''''''.join(split_layer[0] )[:-1] __magic_name__ :Optional[Any] = [tuple(('''metadata''' + split_layer[1]).split('''/''' ) )] elif "kvstore" in layer: __magic_name__ :Union[str, Any] = layer.split('''kvstore''' ) __magic_name__ :int = ''''''.join(split_layer[0] )[:-1] __magic_name__ :List[str] = [tuple(('''kvstore''' + split_layer[1]).split('''/''' ) )] else: __magic_name__ :Dict = layer.split('''/''' ) __magic_name__ :Union[str, Any] = '''/'''.join(split_layer[:-1] ) __magic_name__ :Dict = (split_layer[-1],) if "kvstore/path" in layer: __magic_name__ :Optional[Any] = f'''{switch_checkpoint_path}/{checkpoint_info[layer]}''' elif "kvstore/driver" in layer: __magic_name__ :Optional[Any] = '''file''' else: __magic_name__ :Union[str, Any] = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def __lowercase ( snake_case, snake_case ): """simple docstring""" __magic_name__ :Tuple = rename_keys(snake_case ) __magic_name__ :List[str] = {} for k, v in current_block.items(): __magic_name__ :Union[str, Any] = v __magic_name__ :List[str] = new_current_block torch.save(snake_case, snake_case ) def __lowercase ( snake_case, snake_case, snake_case, snake_case, snake_case = WEIGHTS_NAME ): """simple docstring""" __magic_name__ :Union[str, Any] = convert_file_size_to_int(snake_case ) __magic_name__ :Union[str, Any] = [] __magic_name__ :Optional[Any] = {} __magic_name__ :Optional[int] = 0 __magic_name__ :Optional[int] = 0 os.makedirs(snake_case, exist_ok=snake_case ) with gfile.GFile(switch_checkpoint_path + '''/checkpoint''', '''rb''' ) as fp: __magic_name__ :List[Any] = serialization.msgpack_restore(fp.read() )['''optimizer''']['''target'''] __magic_name__ :List[Any] = flatten_dict(snake_case, sep='''/''' ) __magic_name__ :Any = {} for layer in checkpoint_info.keys(): __magic_name__ , __magic_name__ , __magic_name__ :Optional[Any] = get_key_and_tensorstore_dict( snake_case, snake_case, snake_case ) if curr_real_layer_name in all_layers: __magic_name__ :str = content else: __magic_name__ :Union[str, Any] = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __magic_name__ :Any = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __magic_name__ :str = torch.tensor(snake_case ) __magic_name__ :List[str] = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __magic_name__ , __magic_name__ :Optional[Any] = rename_base_flax_keys(tuple(key.split('''/''' ) ), snake_case ) __magic_name__ :Optional[Any] = '''/'''.join(snake_case ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __magic_name__ :Union[str, Any] = os.path.join( snake_case, weights_name.replace('''.bin''', f'''-{len(snake_case )+1:05d}-of-???.bin''' ) ) rename_and_save_block(snake_case, snake_case ) sharded_state_dicts.append(current_block.keys() ) del current_block __magic_name__ :Union[str, Any] = {} __magic_name__ :List[str] = 0 __magic_name__ :int = raw_weights.to(getattr(snake_case, snake_case ) ) current_block_size += weight_size total_size += weight_size # Add the last block __magic_name__ :int = os.path.join(snake_case, weights_name.replace('''.bin''', f'''-{len(snake_case )+1:05d}-of-???.bin''' ) ) rename_and_save_block(snake_case, snake_case ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(snake_case ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __magic_name__ :Union[str, Any] = {} __magic_name__ :Union[str, Any] = {} for idx, shard in enumerate(snake_case ): __magic_name__ :Union[str, Any] = weights_name.replace( '''.bin''', f'''-{idx+1:05d}-of-{len(snake_case ):05d}.bin''' ) # len(sharded_state_dicts):05d} __magic_name__ :Dict = os.path.join(snake_case, weights_name.replace('''.bin''', f'''-{idx+1:05d}-of-???.bin''' ) ) os.rename(snake_case, os.path.join(snake_case, snake_case ) ) __magic_name__ :str = shard for key in shard: __magic_name__ :List[str] = shard_file # Add the metadata __magic_name__ :List[Any] = {'''total_size''': total_size} __magic_name__ :int = {'''metadata''': metadata, '''weight_map''': weight_map} with open(os.path.join(snake_case, snake_case ), '''w''', encoding='''utf-8''' ) as f: __magic_name__ :Any = json.dumps(snake_case, indent=2, sort_keys=snake_case ) + '''\n''' f.write(snake_case ) return metadata, index if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( """--switch_t5x_checkpoint_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600""", type=str, required=False, help="""Path to a directory containing a folder per layer. Follows the original Google format.""", ) parser.add_argument("""--max_shard_size""", default="""10GB""", required=False, help="""Max shard size""") parser.add_argument("""--dtype""", default="""bfloat16""", type=str, required=False, help="""dtype of the saved model""") parser.add_argument( """--pytorch_dump_folder_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted""", type=str, required=False, help="""Path to the output pytorch model.""", ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def __lowercase ( ): """simple docstring""" from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __magic_name__ :int = SwitchTransformersConfig.from_pretrained('''google/switch-base-8''' ) config.save_pretrained('''/home/arthur_huggingface_co/transformers/switch_converted''' ) __magic_name__ :List[Any] = SwitchTransformersForConditionalGeneration.from_pretrained( '''/home/arthur_huggingface_co/transformers/switch_converted''', device_map='''auto''' ) __magic_name__ :int = TaTokenizer.from_pretrained('''t5-small''' ) __magic_name__ :List[Any] = '''A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.''' __magic_name__ :Optional[Any] = tokenizer(snake_case, return_tensors='''pt''' ).input_ids __magic_name__ :Any = model.generate(snake_case, decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
0
"""simple docstring""" import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py snake_case : Optional[Any] = """.""" # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) snake_case : List[str] = [ """Assert""", """AssignVariableOp""", """EmptyTensorList""", """MergeV2Checkpoints""", """ReadVariableOp""", """ResourceGather""", """RestoreV2""", """SaveV2""", """ShardedFilename""", """StatefulPartitionedCall""", """StaticRegexFullMatch""", """VarHandleOp""", ] def A ( __snake_case: Optional[Any] , __snake_case: Tuple , __snake_case: Any ) -> int: """simple docstring""" __magic_name__ = SavedModel() __magic_name__ = [] with open(os.path.join(__snake_case , 'utils' , 'tf_ops' , 'onnx.json' ) ) as f: __magic_name__ = json.load(__snake_case )['opsets'] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(__snake_case )] ) with open(__snake_case , 'rb' ) as f: saved_model.ParseFromString(f.read() ) __magic_name__ = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want __magic_name__ = sorted(__snake_case ) __magic_name__ = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(__snake_case ) if strict and len(__snake_case ) > 0: raise Exception(F"""Found the following incompatible ops for the opset {opset}:\n""" + incompatible_ops ) elif len(__snake_case ) > 0: print(F"""Found the following incompatible ops for the opset {opset}:""" ) print(*__snake_case , sep='\n' ) else: print(F"""The saved model {saved_model_path} can properly be converted with ONNX.""" ) if __name__ == "__main__": snake_case : Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--saved_model_path""", help="""Path of the saved model to check (the .pb file).""") parser.add_argument( """--opset""", default=1_2, type=int, help="""The ONNX opset against which the model has to be tested.""" ) parser.add_argument( """--framework""", choices=["""onnx"""], default="""onnx""", help="""Frameworks against which to test the saved model.""" ) parser.add_argument( """--strict""", action="""store_true""", help="""Whether make the checking strict (raise errors) or not (raise warnings)""" ) snake_case : Any = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
545
0
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING lowerCAmelCase__ = logging.get_logger(__name__) @add_end_docstrings(_lowercase ) class lowercase ( _lowercase ): """simple docstring""" def __init__( self , **__snake_case): super().__init__(**__snake_case) if self.framework == "tf": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''') requires_backends(self , 'vision') self.check_model_type(__snake_case) def __call__( self , __snake_case , __snake_case = None , **__snake_case , ): if "text_queries" in kwargs: _UpperCamelCase : List[Any] = kwargs.pop('text_queries') if isinstance(__snake_case , (str, Image.Image)): _UpperCamelCase : Union[str, Any] = {'image': image, 'candidate_labels': candidate_labels} else: _UpperCamelCase : int = image _UpperCamelCase : Tuple = super().__call__(__snake_case , **__snake_case) return results def A__ ( self , **__snake_case): _UpperCamelCase : int = {} if "threshold" in kwargs: _UpperCamelCase : Tuple = kwargs['threshold'] if "top_k" in kwargs: _UpperCamelCase : Optional[Any] = kwargs['top_k'] return {}, {}, postprocess_params def A__ ( self , __snake_case): _UpperCamelCase : Dict = load_image(inputs['image']) _UpperCamelCase : Dict = inputs['candidate_labels'] if isinstance(__snake_case , __snake_case): _UpperCamelCase : Tuple = candidate_labels.split(',') _UpperCamelCase : str = torch.tensor([[image.height, image.width]] , dtype=torch.intaa) for i, candidate_label in enumerate(__snake_case): _UpperCamelCase : Optional[Any] = self.tokenizer(__snake_case , return_tensors=self.framework) _UpperCamelCase : int = self.image_processor(__snake_case , return_tensors=self.framework) yield { "is_last": i == len(__snake_case) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def A__ ( self , __snake_case): _UpperCamelCase : Any = model_inputs.pop('target_size') _UpperCamelCase : str = model_inputs.pop('candidate_label') _UpperCamelCase : List[str] = model_inputs.pop('is_last') _UpperCamelCase : Any = self.model(**__snake_case) _UpperCamelCase : List[str] = {'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs} return model_outputs def A__ ( self , __snake_case , __snake_case=0.1 , __snake_case=None): _UpperCamelCase : Union[str, Any] = [] for model_output in model_outputs: _UpperCamelCase : Union[str, Any] = model_output['candidate_label'] _UpperCamelCase : Any = BaseModelOutput(__snake_case) _UpperCamelCase : Union[str, Any] = self.image_processor.post_process_object_detection( outputs=__snake_case , threshold=__snake_case , target_sizes=model_output['target_size'])[0] for index in outputs["scores"].nonzero(): _UpperCamelCase : Optional[Any] = outputs['scores'][index].item() _UpperCamelCase : int = self._get_bounding_box(outputs['boxes'][index][0]) _UpperCamelCase : Optional[int] = {'score': score, 'label': label, 'box': box} results.append(__snake_case) _UpperCamelCase : Any = sorted(__snake_case , key=lambda __snake_case: x["score"] , reverse=__snake_case) if top_k: _UpperCamelCase : str = results[:top_k] return results def A__ ( self , __snake_case): if self.framework != "pt": raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.') _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase : List[Any] = box.int().tolist() _UpperCamelCase : str = { 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax, } return bbox
648
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__ = { """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/config.json""", """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/config.json""", """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/config.json""", """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/config.json""", """bert-base-multilingual-uncased""": """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json""", """bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json""", """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/config.json""", """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/config.json""", """bert-large-uncased-whole-word-masking""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json""" ), """bert-large-cased-whole-word-masking""": ( """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json""" ), """bert-large-uncased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json""" ), """bert-large-cased-whole-word-masking-finetuned-squad""": ( """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json""" ), """bert-base-cased-finetuned-mrpc""": """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json""", """bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json""", """bert-base-german-dbmdz-uncased""": """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json""", """cl-tohoku/bert-base-japanese""": """https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json""", """cl-tohoku/bert-base-japanese-whole-word-masking""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json""" ), """cl-tohoku/bert-base-japanese-char""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json""" ), """cl-tohoku/bert-base-japanese-char-whole-word-masking""": ( """https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json""" ), """TurkuNLP/bert-base-finnish-cased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json""" ), """TurkuNLP/bert-base-finnish-uncased-v1""": ( """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json""" ), """wietsedv/bert-base-dutch-cased""": """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json""", # See all BERT models at https://huggingface.co/models?filter=bert } class lowercase ( _lowercase ): """simple docstring""" a__ = "bert" def __init__( self , __snake_case=3_05_22 , __snake_case=7_68 , __snake_case=12 , __snake_case=12 , __snake_case=30_72 , __snake_case="gelu" , __snake_case=0.1 , __snake_case=0.1 , __snake_case=5_12 , __snake_case=2 , __snake_case=0.0_2 , __snake_case=1e-12 , __snake_case=0 , __snake_case="absolute" , __snake_case=True , __snake_case=None , **__snake_case , ): super().__init__(pad_token_id=__snake_case , **__snake_case) _UpperCamelCase : int = vocab_size _UpperCamelCase : Optional[Any] = hidden_size _UpperCamelCase : Optional[Any] = num_hidden_layers _UpperCamelCase : List[str] = num_attention_heads _UpperCamelCase : int = hidden_act _UpperCamelCase : Optional[Any] = intermediate_size _UpperCamelCase : Union[str, Any] = hidden_dropout_prob _UpperCamelCase : Tuple = attention_probs_dropout_prob _UpperCamelCase : Optional[int] = max_position_embeddings _UpperCamelCase : str = type_vocab_size _UpperCamelCase : Optional[Any] = initializer_range _UpperCamelCase : List[str] = layer_norm_eps _UpperCamelCase : Any = position_embedding_type _UpperCamelCase : Any = use_cache _UpperCamelCase : Any = classifier_dropout class lowercase ( _lowercase ): """simple docstring""" @property def A__ ( self): if self.task == "multiple-choice": _UpperCamelCase : Union[str, Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _UpperCamelCase : Optional[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ])
648
1
"""simple docstring""" def _snake_case ( snake_case__ : int = 1000 ): A = 2**power A = 0 while n: A , A = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
91
'''simple docstring''' import os import time import pytest from datasets.utils.filelock import FileLock, Timeout def _A ( A__ ): """simple docstring""" __lowercase = FileLock(str(tmpdir / '''foo.lock''' ) ) __lowercase = FileLock(str(tmpdir / '''foo.lock''' ) ) __lowercase = 0.0_1 with locka.acquire(): with pytest.raises(A__ ): __lowercase = time.time() locka.acquire(A__ ) assert time.time() - _start > timeout def _A ( A__ ): """simple docstring""" __lowercase = '''a''' * 1000 + '''.lock''' __lowercase = FileLock(str(tmpdir / filename ) ) assert locka._lock_file.endswith('''.lock''' ) assert not locka._lock_file.endswith(A__ ) assert len(os.path.basename(locka._lock_file ) ) <= 255 __lowercase = FileLock(tmpdir / filename ) with locka.acquire(): with pytest.raises(A__ ): locka.acquire(0 )
41
0
"""simple docstring""" def lowerCamelCase_(__SCREAMING_SNAKE_CASE )-> str: _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 # if input_string is "aba" than new_input_string become "a|b|a" _SCREAMING_SNAKE_CASE : List[str] = """""" _SCREAMING_SNAKE_CASE : Dict = """""" # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(__SCREAMING_SNAKE_CASE ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Any = 0, 0 # length[i] shows the length of palindromic substring with center i _SCREAMING_SNAKE_CASE : str = [1 for i in range(len(__SCREAMING_SNAKE_CASE ) )] # for each character in new_string find corresponding palindromic string _SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for j in range(len(__SCREAMING_SNAKE_CASE ) ): _SCREAMING_SNAKE_CASE : str = 1 if j > r else min(length[l + r - j] // 2 , r - j + 1 ) while ( j - k >= 0 and j + k < len(__SCREAMING_SNAKE_CASE ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 _SCREAMING_SNAKE_CASE : List[Any] = 2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: _SCREAMING_SNAKE_CASE : List[str] = j - k + 1 # noqa: E741 _SCREAMING_SNAKE_CASE : str = j + k - 1 # update max_length and start position if max_length < length[j]: _SCREAMING_SNAKE_CASE : Optional[int] = length[j] _SCREAMING_SNAKE_CASE : Any = j # create that string _SCREAMING_SNAKE_CASE : Dict = new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
635
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _snake_case ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : str): """simple docstring""" _SCREAMING_SNAKE_CASE : Any = AutoImageProcessor.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") _SCREAMING_SNAKE_CASE : str = AutoModelForImageClassification.from_pretrained("""microsoft/dit-base-finetuned-rvlcdip""") model.to(_A) from datasets import load_dataset _SCREAMING_SNAKE_CASE : Any = load_dataset("""nielsr/rvlcdip-demo""") _SCREAMING_SNAKE_CASE : Any = dataset["""train"""][0]["""image"""].convert("""RGB""") _SCREAMING_SNAKE_CASE : str = image_processor(_A , return_tensors="""pt""").to(_A) # forward pass with torch.no_grad(): _SCREAMING_SNAKE_CASE : Any = model(**_A) _SCREAMING_SNAKE_CASE : List[Any] = outputs.logits _SCREAMING_SNAKE_CASE : List[str] = torch.Size((1, 1_6)) self.assertEqual(logits.shape , _A) _SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=_A , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , _A , atol=1e-4))
635
1
"""simple docstring""" import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def _lowercase ( __snake_case ,__snake_case ,__snake_case ,__snake_case ,__snake_case ) -> int: # Load configuration defined in the metadata file with open(__snake_case ) as metadata_file: __lowerCAmelCase : Optional[Any] = json.load(__snake_case ) __lowerCAmelCase : Optional[int] = LukeConfig(use_entity_aware_attention=__snake_case ,**metadata["model_config"] ) # Load in the weights from the checkpoint_path __lowerCAmelCase : int = torch.load(__snake_case ,map_location="cpu" )["module"] # Load the entity vocab file __lowerCAmelCase : Optional[int] = load_original_entity_vocab(__snake_case ) # add an entry for [MASK2] __lowerCAmelCase : str = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 __lowerCAmelCase : List[Any] = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks __lowerCAmelCase : Any = AddedToken("<ent>" ,lstrip=__snake_case ,rstrip=__snake_case ) __lowerCAmelCase : Optional[int] = AddedToken("<ent2>" ,lstrip=__snake_case ,rstrip=__snake_case ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F"""Saving tokenizer to {pytorch_dump_folder_path}""" ) tokenizer.save_pretrained(__snake_case ) with open(os.path.join(__snake_case ,"tokenizer_config.json" ) ,"r" ) as f: __lowerCAmelCase : Optional[int] = json.load(__snake_case ) __lowerCAmelCase : Tuple = "MLukeTokenizer" with open(os.path.join(__snake_case ,"tokenizer_config.json" ) ,"w" ) as f: json.dump(__snake_case ,__snake_case ) with open(os.path.join(__snake_case ,MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) ,"w" ) as f: json.dump(__snake_case ,__snake_case ) __lowerCAmelCase : Tuple = MLukeTokenizer.from_pretrained(__snake_case ) # Initialize the embeddings of the special tokens __lowerCAmelCase : List[Any] = tokenizer.convert_tokens_to_ids(["@"] )[0] __lowerCAmelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(["#"] )[0] __lowerCAmelCase : str = state_dict["embeddings.word_embeddings.weight"] __lowerCAmelCase : Tuple = word_emb[ent_init_index].unsqueeze(0 ) __lowerCAmelCase : Any = word_emb[enta_init_index].unsqueeze(0 ) __lowerCAmelCase : str = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: __lowerCAmelCase : str = state_dict[bias_name] __lowerCAmelCase : Any = decoder_bias[ent_init_index].unsqueeze(0 ) __lowerCAmelCase : List[Any] = decoder_bias[enta_init_index].unsqueeze(0 ) __lowerCAmelCase : Optional[int] = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: __lowerCAmelCase : Optional[int] = F"""encoder.layer.{layer_index}.attention.self.""" __lowerCAmelCase : Tuple = state_dict[prefix + matrix_name] __lowerCAmelCase : List[str] = state_dict[prefix + matrix_name] __lowerCAmelCase : Dict = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks __lowerCAmelCase : List[Any] = state_dict["entity_embeddings.entity_embeddings.weight"] __lowerCAmelCase : int = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) __lowerCAmelCase : Any = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' __lowerCAmelCase : Dict = state_dict["entity_predictions.bias"] __lowerCAmelCase : Dict = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) __lowerCAmelCase : Optional[Any] = torch.cat([entity_prediction_bias, entity_mask_bias] ) __lowerCAmelCase : Union[str, Any] = LukeForMaskedLM(config=__snake_case ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) __lowerCAmelCase : Dict = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): __lowerCAmelCase : Optional[int] = state_dict[key] else: __lowerCAmelCase : int = state_dict[key] __lowerCAmelCase , __lowerCAmelCase : int = model.load_state_dict(__snake_case ,strict=__snake_case ) if set(__snake_case ) != {"luke.embeddings.position_ids"}: raise ValueError(F"""Unexpected unexpected_keys: {unexpected_keys}""" ) if set(__snake_case ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F"""Unexpected missing_keys: {missing_keys}""" ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs __lowerCAmelCase : Any = MLukeTokenizer.from_pretrained(__snake_case ,task="entity_classification" ) __lowerCAmelCase : Union[str, Any] = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." __lowerCAmelCase : Optional[Any] = (0, 9) __lowerCAmelCase : Any = tokenizer(__snake_case ,entity_spans=[span] ,return_tensors="pt" ) __lowerCAmelCase : Tuple = model(**__snake_case ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base __lowerCAmelCase : Dict = torch.Size((1, 33, 768) ) __lowerCAmelCase : str = torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F"""Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}""" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] ,__snake_case ,atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base __lowerCAmelCase : Dict = torch.Size((1, 1, 768) ) __lowerCAmelCase : Tuple = torch.tensor([[-0.1482, 0.0609, 0.0322]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F"""Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is""" F""" {expected_shape}""" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] ,__snake_case ,atol=1e-4 ): raise ValueError # Verify masked word/entity prediction __lowerCAmelCase : int = MLukeTokenizer.from_pretrained(__snake_case ) __lowerCAmelCase : List[str] = "Tokyo is the capital of <mask>." __lowerCAmelCase : List[Any] = (24, 30) __lowerCAmelCase : Tuple = tokenizer(__snake_case ,entity_spans=[span] ,return_tensors="pt" ) __lowerCAmelCase : Any = model(**__snake_case ) __lowerCAmelCase : List[Any] = encoding["input_ids"][0].tolist() __lowerCAmelCase : List[str] = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) __lowerCAmelCase : Optional[int] = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(__snake_case ) __lowerCAmelCase : int = outputs.entity_logits[0][0].argmax().item() __lowerCAmelCase : int = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(__snake_case ) ) model.save_pretrained(__snake_case ) def _lowercase ( __snake_case ) -> List[str]: __lowerCAmelCase : Optional[int] = ["[MASK]", "[PAD]", "[UNK]"] __lowerCAmelCase : List[Any] = [json.loads(__snake_case ) for line in open(__snake_case )] __lowerCAmelCase : Dict = {} for entry in data: __lowerCAmelCase : List[Any] = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: __lowerCAmelCase : List[str] = entity_id break __lowerCAmelCase : Tuple = F"""{language}:{entity_name}""" __lowerCAmelCase : Union[str, Any] = entity_id return new_mapping if __name__ == "__main__": __snake_case : Any = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) __snake_case : List[Any] = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
293
"""simple docstring""" from math import factorial class A__ : '''simple docstring''' def __init__( self: str , _SCREAMING_SNAKE_CASE: Tuple , _SCREAMING_SNAKE_CASE: Any) -> str: """simple docstring""" __lowerCAmelCase : str = real if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): __lowerCAmelCase : Optional[int] = [1] * rank else: __lowerCAmelCase : Optional[Any] = rank def __repr__( self: Optional[int]) -> List[str]: """simple docstring""" return ( F"""{self.real}+""" F"""{'+'.join(str(_SCREAMING_SNAKE_CASE)+'E'+str(n+1)for n,dual in enumerate(self.duals))}""" ) def _SCREAMING_SNAKE_CASE ( self: List[str]) -> Union[str, Any]: """simple docstring""" __lowerCAmelCase : List[str] = self.duals.copy() while cur[-1] == 0: cur.pop(-1) return Dual(self.real , _SCREAMING_SNAKE_CASE) def __add__( self: Optional[int] , _SCREAMING_SNAKE_CASE: Tuple) -> Union[str, Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): return Dual(self.real + other , self.duals) __lowerCAmelCase : int = self.duals.copy() __lowerCAmelCase : List[Any] = other.duals.copy() if len(_SCREAMING_SNAKE_CASE) > len(_SCREAMING_SNAKE_CASE): o_dual.extend([1] * (len(_SCREAMING_SNAKE_CASE) - len(_SCREAMING_SNAKE_CASE))) elif len(_SCREAMING_SNAKE_CASE) < len(_SCREAMING_SNAKE_CASE): s_dual.extend([1] * (len(_SCREAMING_SNAKE_CASE) - len(_SCREAMING_SNAKE_CASE))) __lowerCAmelCase : Tuple = [] for i in range(len(_SCREAMING_SNAKE_CASE)): new_duals.append(s_dual[i] + o_dual[i]) return Dual(self.real + other.real , _SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = __add__ def __sub__( self: Dict , _SCREAMING_SNAKE_CASE: str) -> Optional[Any]: """simple docstring""" return self + other * -1 def __mul__( self: str , _SCREAMING_SNAKE_CASE: Tuple) -> Optional[int]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): __lowerCAmelCase : List[Any] = [] for i in self.duals: new_duals.append(i * other) return Dual(self.real * other , _SCREAMING_SNAKE_CASE) __lowerCAmelCase : List[str] = [0] * (len(self.duals) + len(other.duals) + 1) for i, item in enumerate(self.duals): for j, jtem in enumerate(other.duals): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals)): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals)): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real , _SCREAMING_SNAKE_CASE) SCREAMING_SNAKE_CASE = __mul__ def __truediv__( self: Any , _SCREAMING_SNAKE_CASE: str) -> Dict: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): __lowerCAmelCase : List[str] = [] for i in self.duals: new_duals.append(i / other) return Dual(self.real / other , _SCREAMING_SNAKE_CASE) raise ValueError def __floordiv__( self: List[Any] , _SCREAMING_SNAKE_CASE: Tuple) -> str: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): __lowerCAmelCase : str = [] for i in self.duals: new_duals.append(i // other) return Dual(self.real // other , _SCREAMING_SNAKE_CASE) raise ValueError def __pow__( self: Optional[Any] , _SCREAMING_SNAKE_CASE: Tuple) -> List[Any]: """simple docstring""" if n < 0 or isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): raise ValueError("power must be a positive integer") if n == 0: return 1 if n == 1: return self __lowerCAmelCase : List[Any] = self for _ in range(n - 1): x *= self return x def _lowercase ( __snake_case ,__snake_case ,__snake_case ) -> Any: if not callable(__snake_case ): raise ValueError("differentiate() requires a function as input for func" ) if not isinstance(__snake_case ,(float, int) ): raise ValueError("differentiate() requires a float as input for position" ) if not isinstance(__snake_case ,__snake_case ): raise ValueError("differentiate() requires an int as input for order" ) __lowerCAmelCase : Any = Dual(__snake_case ,1 ) __lowerCAmelCase : Tuple = func(__snake_case ) if order == 0: return result.real return result.duals[order - 1] * factorial(__snake_case ) if __name__ == "__main__": import doctest doctest.testmod() def _lowercase ( __snake_case ) -> Tuple: return y**2 * y**4 print(differentiate(f, 9, 2))
293
1
'''simple docstring''' from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable A = {'configuration_gpt_neox': ['GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXConfig']} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = ['GPTNeoXTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A = [ 'GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoXForCausalLM', 'GPTNeoXForQuestionAnswering', 'GPTNeoXForSequenceClassification', 'GPTNeoXForTokenClassification', 'GPTNeoXLayer', 'GPTNeoXModel', 'GPTNeoXPreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox import ( GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXLayer, GPTNeoXModel, GPTNeoXPreTrainedModel, ) else: import sys A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
709
'''simple docstring''' import numpy as np def UpperCAmelCase ( UpperCAmelCase__ : np.array): return 1 / (1 + np.exp(-vector)) if __name__ == "__main__": import doctest doctest.testmod()
449
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase__ : List[str] = { 'configuration_clipseg': [ 'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPSegConfig', 'CLIPSegTextConfig', 'CLIPSegVisionConfig', ], 'processing_clipseg': ['CLIPSegProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : Optional[Any] = [ 'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST', 'CLIPSegModel', 'CLIPSegPreTrainedModel', 'CLIPSegTextModel', 'CLIPSegVisionModel', 'CLIPSegForImageSegmentation', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys lowercase__ : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
98
class lowerCamelCase_ : def __init__( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Tuple: """simple docstring""" _UpperCamelCase = None _UpperCamelCase = None _UpperCamelCase = graph self._normalize_graph(lowerCamelCase_ , lowerCamelCase_ ) _UpperCamelCase = len(lowerCamelCase_ ) _UpperCamelCase = None def lowercase ( self , lowerCamelCase_ , lowerCamelCase_ ) -> str: """simple docstring""" if sources is int: _UpperCamelCase = [sources] if sinks is int: _UpperCamelCase = [sinks] if len(lowerCamelCase_ ) == 0 or len(lowerCamelCase_ ) == 0: return _UpperCamelCase = sources[0] _UpperCamelCase = sinks[0] # make fake vertex if there are more # than one source or sink if len(lowerCamelCase_ ) > 1 or len(lowerCamelCase_ ) > 1: _UpperCamelCase = 0 for i in sources: max_input_flow += sum(self.graph[i] ) _UpperCamelCase = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: _UpperCamelCase = max_input_flow _UpperCamelCase = 0 _UpperCamelCase = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: _UpperCamelCase = max_input_flow _UpperCamelCase = size - 1 def lowercase ( self ) -> Union[str, Any]: """simple docstring""" if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before." ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def lowercase ( self , lowerCamelCase_ ) -> List[str]: """simple docstring""" _UpperCamelCase = algorithm(self ) class lowerCamelCase_ : def __init__( self , lowerCamelCase_ ) -> Tuple: """simple docstring""" _UpperCamelCase = flow_network _UpperCamelCase = flow_network.verticesCount _UpperCamelCase = flow_network.sourceIndex _UpperCamelCase = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that _UpperCamelCase = flow_network.graph _UpperCamelCase = False def lowercase ( self ) -> Optional[Any]: """simple docstring""" if not self.executed: self._algorithm() _UpperCamelCase = True def lowercase ( self ) -> List[str]: """simple docstring""" pass class lowerCamelCase_ ( lowercase ): def __init__( self , lowerCamelCase_ ) -> Dict: """simple docstring""" super().__init__(lowerCamelCase_ ) # use this to save your result _UpperCamelCase = -1 def lowercase ( self ) -> List[str]: """simple docstring""" if not self.executed: raise Exception("You should execute algorithm before using its result!" ) return self.maximum_flow class lowerCamelCase_ ( lowercase ): def __init__( self , lowerCamelCase_ ) -> List[str]: """simple docstring""" super().__init__(lowerCamelCase_ ) _UpperCamelCase = [[0] * self.verticies_count for i in range(self.verticies_count )] _UpperCamelCase = [0] * self.verticies_count _UpperCamelCase = [0] * self.verticies_count def lowercase ( self ) -> int: """simple docstring""" _UpperCamelCase = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule _UpperCamelCase = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list _UpperCamelCase = 0 while i < len(lowerCamelCase_ ): _UpperCamelCase = vertices_list[i] _UpperCamelCase = self.heights[vertex_index] self.process_vertex(lowerCamelCase_ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(lowerCamelCase_ ) ) _UpperCamelCase = 0 else: i += 1 _UpperCamelCase = sum(self.preflow[self.source_index] ) def lowercase ( self , lowerCamelCase_ ) -> int: """simple docstring""" while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(lowerCamelCase_ , lowerCamelCase_ ) self.relabel(lowerCamelCase_ ) def lowercase ( self , lowerCamelCase_ , lowerCamelCase_ ) -> Dict: """simple docstring""" _UpperCamelCase = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def lowercase ( self , lowerCamelCase_ ) -> Tuple: """simple docstring""" _UpperCamelCase = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): _UpperCamelCase = self.heights[to_index] if min_height is not None: _UpperCamelCase = min_height + 1 if __name__ == "__main__": __lowerCAmelCase = [0] __lowerCAmelCase = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] __lowerCAmelCase = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network __lowerCAmelCase = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate __lowerCAmelCase = flow_network.find_maximum_flow() print(F'''maximum flow is {maximum_flow}''')
147
0
'''simple docstring''' from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_tf_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_tf_available(): import tensorflow as tf _lowercase : Optional[int] = logging.get_logger(__name__) @dataclass class __magic_name__ ( _UpperCAmelCase): UpperCamelCase__ = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__( self : Optional[Any] , **lowercase_ : Tuple ): for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: lowercase_ : Dict = deprecated_arg[3:] lowercase_ : Dict = not kwargs.pop(lowercase_ ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no-{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) lowercase_ : Optional[Any] = kwargs.pop("""tpu_name""" , self.tpu_name ) lowercase_ : Optional[int] = kwargs.pop("""device_idx""" , self.device_idx ) lowercase_ : List[Any] = kwargs.pop("""eager_mode""" , self.eager_mode ) lowercase_ : Dict = kwargs.pop("""use_xla""" , self.use_xla ) super().__init__(**lowercase_ ) UpperCamelCase__ = field( default=_UpperCAmelCase, metadata={'''help''': '''Name of TPU'''}, ) UpperCamelCase__ = field( default=0, metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''}, ) UpperCamelCase__ = field(default=_UpperCAmelCase, metadata={'''help''': '''Benchmark models in eager model.'''}) UpperCamelCase__ = field( default=_UpperCAmelCase, metadata={ '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.''' }, ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ): requires_backends(self , ["""tf"""] ) lowercase_ : Tuple = None if self.tpu: try: if self.tpu_name: lowercase_ : Optional[int] = tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name ) else: lowercase_ : Union[str, Any] = tf.distribute.cluster_resolver.TPUClusterResolver() except ValueError: lowercase_ : Optional[int] = None return tpu @cached_property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): requires_backends(self , ["""tf"""] ) if self.is_tpu: tf.config.experimental_connect_to_cluster(self._setup_tpu ) tf.tpu.experimental.initialize_tpu_system(self._setup_tpu ) lowercase_ : str = tf.distribute.TPUStrategy(self._setup_tpu ) else: # currently no multi gpu is allowed if self.is_gpu: # TODO: Currently only single GPU is supported tf.config.set_visible_devices(self.gpu_list[self.device_idx] , """GPU""" ) lowercase_ : Union[str, Any] = tf.distribute.OneDeviceStrategy(device=f'''/gpu:{self.device_idx}''' ) else: tf.config.set_visible_devices([] , """GPU""" ) # disable GPU lowercase_ : Dict = tf.distribute.OneDeviceStrategy(device=f'''/cpu:{self.device_idx}''' ) return strategy @property def SCREAMING_SNAKE_CASE_ ( self : int ): requires_backends(self , ["""tf"""] ) return self._setup_tpu is not None @property def SCREAMING_SNAKE_CASE_ ( self : Any ): requires_backends(self , ["""tf"""] ) return self._setup_strategy @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ): requires_backends(self , ["""tf"""] ) return tf.config.list_physical_devices("""GPU""" ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): requires_backends(self , ["""tf"""] ) if self.cuda: return len(self.gpu_list ) return 0 @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ): return self.n_gpu > 0
30
'''simple docstring''' import argparse import intel_extension_for_pytorch as ipex import torch from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline _lowercase : Optional[Any] = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False) parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not") parser.add_argument("--steps", default=None, type=int, help="Num inference steps") _lowercase : Dict = parser.parse_args() _lowercase : Dict = "cpu" _lowercase : str = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings" _lowercase : Any = "path-to-your-trained-model" _lowercase : str = StableDiffusionPipeline.from_pretrained(model_id) if args.dpm: _lowercase : Optional[int] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config) _lowercase : Any = pipe.to(device) # to channels last _lowercase : Union[str, Any] = pipe.unet.to(memory_format=torch.channels_last) _lowercase : List[Any] = pipe.vae.to(memory_format=torch.channels_last) _lowercase : Union[str, Any] = pipe.text_encoder.to(memory_format=torch.channels_last) if pipe.requires_safety_checker: _lowercase : Tuple = pipe.safety_checker.to(memory_format=torch.channels_last) # optimize with ipex _lowercase : int = torch.randn(2, 4, 64, 64) _lowercase : int = torch.rand(1) * 999 _lowercase : Union[str, Any] = torch.randn(2, 77, 768) _lowercase : Optional[Any] = (sample, timestep, encoder_hidden_status) try: _lowercase : int = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example) except Exception: _lowercase : Optional[int] = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True) _lowercase : List[Any] = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True) _lowercase : str = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True) if pipe.requires_safety_checker: _lowercase : int = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True) # compute _lowercase : int = 666 _lowercase : Any = torch.Generator(device).manual_seed(seed) _lowercase : int = {"generator": generator} if args.steps is not None: _lowercase : Optional[int] = args.steps with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa): _lowercase : List[Any] = pipe(prompt, **generate_kwargs).images[0] # save image image.save("generated.png")
30
1
'''simple docstring''' import argparse import re from flax.traverse_util import flatten_dict, unflatten_dict from tax import checkpoints from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model from transformers.utils import logging logging.set_verbosity_info() # should not include what is already done by the `from_pt` argument a_ = { '/attention/': '/0/SelfAttention/', '/self_attention/': '/0/SelfAttention/', '/encoder_decoder_attention/': '/1/EncDecAttention/', 'value': 'v', 'query': 'q', 'key': 'k', 'out': 'o', 'pre_self_attention_layer_norm': '0/layer_norm', 'pre_cross_attention_layer_norm': '1/layer_norm', 'pre_attention_layer_norm': '0/layer_norm', # previously 1, but seems wrong 'token_embedder': 'shared', 'encoder_norm': 'final_layer_norm', 'decoder_norm': 'final_layer_norm', 'relpos_bias/rel_embedding': 'block/0/layer/0/SelfAttention/relative_attention_bias/weight', 'router/router_weights/w/': 'router/classifier/', 'roer/roer_weights/w/': 'router/classifier/', 'logits_dense': 'lm_head', } def _a( UpperCamelCase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any =list(s_dict.keys() ) for key in keys: SCREAMING_SNAKE_CASE__ : Dict =R'''.*/layers_(\d+)''' SCREAMING_SNAKE_CASE__ : int =key if re.match(UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : List[Any] =re.sub(R'''layers_(\d+)''', R'''block/\1/layer''', UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Any =R'''(encoder|decoder)\/''' if re.match(UpperCamelCase__, UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Dict =re.match(UpperCamelCase__, UpperCamelCase__ ).groups() if groups[0] == "encoder": SCREAMING_SNAKE_CASE__ : Dict =re.sub(R'''/mlp/''', R'''/1/mlp/''', UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =re.sub(R'''/pre_mlp_layer_norm/''', R'''/1/layer_norm/''', UpperCamelCase__ ) elif groups[0] == "decoder": SCREAMING_SNAKE_CASE__ : Any =re.sub(R'''/mlp/''', R'''/2/mlp/''', UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] =re.sub(R'''/pre_mlp_layer_norm/''', R'''/2/layer_norm/''', UpperCamelCase__ ) # 2. Convert other classic mappings for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items(): if old_key in new_key: SCREAMING_SNAKE_CASE__ : Optional[int] =new_key.replace(UpperCamelCase__, UpperCamelCase__ ) print(f"{key} -> {new_key}" ) SCREAMING_SNAKE_CASE__ : Dict =s_dict.pop(UpperCamelCase__ ) if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: SCREAMING_SNAKE_CASE__ : str =s_dict[ '''encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight''' ].T if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict: SCREAMING_SNAKE_CASE__ : Dict =s_dict[ '''decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight''' ].T # 3. Take extra care of the EXPERTS layer for key in list(s_dict.keys() ): if "expert" in key: SCREAMING_SNAKE_CASE__ : Union[str, Any] =s_dict[key].shape[0] SCREAMING_SNAKE_CASE__ : List[str] =s_dict[key] for idx in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] =expert_weihts[idx] print(f"{key} -> {key.replace('expert/', 'nested fstring' )}" ) s_dict.pop(UpperCamelCase__ ) return s_dict a_ = { 'NUM_ENCODER_LAYERS': 'num_layers', 'NUM_DECODER_LAYERS': 'num_decoder_layers', 'NUM_HEADS': 'num_heads', 'HEAD_DIM': 'd_kv', 'EMBED_DIM': 'd_model', 'MLP_DIM': 'd_ff', 'NUM_SELECTED_EXPERTS': 'num_selected_experts', 'NUM_ENCODER_SPARSE_LAYERS': 'num_sparse_encoder_layers', 'NUM_DECODER_SPARSE_LAYERS': 'num_sparse_decoder_layers', 'dense.MlpBlock.activations': 'feed_forward_proj', } def _a( UpperCamelCase__ : Optional[Any], UpperCamelCase__ : Optional[int] ): '''simple docstring''' import regex as re with open(UpperCamelCase__, '''r''' ) as f: SCREAMING_SNAKE_CASE__ : Optional[Any] =f.read() SCREAMING_SNAKE_CASE__ : Optional[int] =re.findall(R'''(.*) = ([0-9.]*)''', UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] ={} for param, value in regex_match: if param in GIN_TO_CONFIG_MAPPING and value != "": SCREAMING_SNAKE_CASE__ : Union[str, Any] =float(UpperCamelCase__ ) if '''.''' in value else int(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : Dict =re.findall(R'''(.*activations) = \(\'(.*)\',\)''', UpperCamelCase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] =str(activation[1] ) SCREAMING_SNAKE_CASE__ : str =num_experts SCREAMING_SNAKE_CASE__ : Dict =SwitchTransformersConfig(**UpperCamelCase__ ) return config def _a( UpperCamelCase__ : str, UpperCamelCase__ : int, UpperCamelCase__ : Any=None, UpperCamelCase__ : int="./", UpperCamelCase__ : List[str]=8 ): '''simple docstring''' print(f"Loading flax weights from : {flax_checkpoint_path}" ) SCREAMING_SNAKE_CASE__ : Any =checkpoints.load_tax_checkpoint(UpperCamelCase__ ) if gin_file is not None: SCREAMING_SNAKE_CASE__ : Optional[int] =convert_gin_to_config(UpperCamelCase__, UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ : Tuple =SwitchTransformersConfig.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =SwitchTransformersForConditionalGeneration(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : str =flax_params['''target'''] SCREAMING_SNAKE_CASE__ : List[Any] =flatten_dict(UpperCamelCase__, sep='''/''' ) SCREAMING_SNAKE_CASE__ : Dict =rename_keys(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =unflatten_dict(UpperCamelCase__, sep='''/''' ) # Load the flax params in the PT model load_flax_weights_in_pytorch_model(UpperCamelCase__, UpperCamelCase__ ) print(f"Save PyTorch model to {pytorch_dump_path}" ) pt_model.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--switch_t5x_checkpoint_path', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the' ' model architecture. If not provided, a `gin_file` has to be provided.' ), ) parser.add_argument( '--gin_file', default=None, type=str, required=False, help='Path to the gin config file. If not provided, a `config_file` has to be passed ', ) parser.add_argument( '--config_name', default=None, type=str, required=False, help='Config name of SwitchTransformers model.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output pytorch model.' ) parser.add_argument('--num_experts', default=8, type=int, required=False, help='Number of experts') a_ = parser.parse_args() convert_flax_checkpoint_to_pytorch( args.switch_tax_checkpoint_path, args.config_name, args.gin_file, args.pytorch_dump_folder_path, args.num_experts, )
296
'''simple docstring''' def _a( UpperCamelCase__ : int = 1_0, UpperCamelCase__ : int = 2_2 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str =range(1, UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ : List[str] =range(1, UpperCamelCase__ ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(F'''{solution(1_0, 2_2) = }''')
296
1
import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowerCAmelCase__ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowerCAmelCase__ ( UpperCAmelCase ): """simple docstring""" from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(UpperCAmelCase ) def lowerCAmelCase__ ( UpperCAmelCase ): """simple docstring""" from diffusers.utils.testing_utils import pytest_terminal_summary_main snake_case__ : Optional[Any] = terminalreporter.config.getoption("""--make-reports""" ) if make_reports: pytest_terminal_summary_main(UpperCAmelCase , id=UpperCAmelCase )
713
'''simple docstring''' import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class _A : '''simple docstring''' @property def __lowerCAmelCase ( self : List[str] )-> Any: return self.get_dummy_input() @property def __lowerCAmelCase ( self : int )-> Optional[Any]: if self.block_type == "down": return (4, 32, 16, 16) elif self.block_type == "mid": return (4, 32, 32, 32) elif self.block_type == "up": return (4, 32, 64, 64) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def __lowerCAmelCase ( self : Any , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : List[str]=False , lowerCamelCase : int=False , lowerCamelCase : str=False , )-> Optional[int]: snake_case__ : Dict = 4 snake_case__ : Optional[int] = 32 snake_case__ : Tuple = (32, 32) snake_case__ : List[str] = torch.manual_seed(0 ) snake_case__ : List[str] = torch.device(lowerCamelCase ) snake_case__ : Optional[int] = (batch_size, num_channels) + sizes snake_case__ : Tuple = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=lowerCamelCase ) snake_case__ : str = {"""hidden_states""": hidden_states} if include_temb: snake_case__ : Optional[int] = 128 snake_case__ : str = randn_tensor((batch_size, temb_channels) , generator=lowerCamelCase , device=lowerCamelCase ) if include_res_hidden_states_tuple: snake_case__ : List[str] = torch.manual_seed(1 ) snake_case__ : Optional[Any] = (randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=lowerCamelCase ),) if include_encoder_hidden_states: snake_case__ : List[Any] = floats_tensor((batch_size, 32, 32) ).to(lowerCamelCase ) if include_skip_sample: snake_case__ : List[Any] = randn_tensor(((batch_size, 3) + sizes) , generator=lowerCamelCase , device=lowerCamelCase ) return dummy_input def __lowerCAmelCase ( self : int )-> int: snake_case__ : List[Any] = { """in_channels""": 32, """out_channels""": 32, """temb_channels""": 128, } if self.block_type == "up": snake_case__ : Any = 32 if self.block_type == "mid": init_dict.pop("""out_channels""" ) snake_case__ : int = self.dummy_input return init_dict, inputs_dict def __lowerCAmelCase ( self : int , lowerCamelCase : List[Any] )-> Optional[Any]: snake_case__ , snake_case__ : Union[str, Any] = self.prepare_init_args_and_inputs_for_common() snake_case__ : int = self.block_class(**lowerCamelCase ) unet_block.to(lowerCamelCase ) unet_block.eval() with torch.no_grad(): snake_case__ : str = unet_block(**lowerCamelCase ) if isinstance(lowerCamelCase , lowerCamelCase ): snake_case__ : int = output[0] self.assertEqual(output.shape , self.output_shape ) snake_case__ : Union[str, Any] = output[0, -1, -3:, -3:] snake_case__ : Dict = torch.tensor(lowerCamelCase ).to(lowerCamelCase ) assert torch_all_close(output_slice.flatten() , lowerCamelCase , atol=5e-3 ) @unittest.skipIf(torch_device == """mps""" , """Training is not supported in mps""" ) def __lowerCAmelCase ( self : List[Any] )-> List[Any]: snake_case__ , snake_case__ : List[Any] = self.prepare_init_args_and_inputs_for_common() snake_case__ : Dict = self.block_class(**lowerCamelCase ) model.to(lowerCamelCase ) model.train() snake_case__ : Union[str, Any] = model(**lowerCamelCase ) if isinstance(lowerCamelCase , lowerCamelCase ): snake_case__ : Tuple = output[0] snake_case__ : List[str] = torch.device(lowerCamelCase ) snake_case__ : Optional[Any] = randn_tensor(output.shape , device=lowerCamelCase ) snake_case__ : Tuple = torch.nn.functional.mse_loss(lowerCamelCase , lowerCamelCase ) loss.backward()
172
0
"""simple docstring""" import unittest from transformers import MraConfig, 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, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class A_ : def __init__( self: Optional[int] ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: int=2 ,__lowerCAmelCase: Dict=8 ,__lowerCAmelCase: List[Any]=True ,__lowerCAmelCase: List[str]=True ,__lowerCAmelCase: List[Any]=True ,__lowerCAmelCase: Dict=True ,__lowerCAmelCase: Any=99 ,__lowerCAmelCase: int=16 ,__lowerCAmelCase: List[Any]=5 ,__lowerCAmelCase: List[str]=2 ,__lowerCAmelCase: str=36 ,__lowerCAmelCase: List[str]="gelu" ,__lowerCAmelCase: Any=0.0 ,__lowerCAmelCase: List[str]=0.0 ,__lowerCAmelCase: Any=512 ,__lowerCAmelCase: Union[str, Any]=16 ,__lowerCAmelCase: str=2 ,__lowerCAmelCase: str=0.02 ,__lowerCAmelCase: Dict=3 ,__lowerCAmelCase: List[str]=4 ,__lowerCAmelCase: Tuple=None ,): '''simple docstring''' _lowerCamelCase : Tuple = parent _lowerCamelCase : Union[str, Any] = batch_size _lowerCamelCase : Optional[Any] = seq_length _lowerCamelCase : int = is_training _lowerCamelCase : List[Any] = use_input_mask _lowerCamelCase : Dict = use_token_type_ids _lowerCamelCase : Tuple = use_labels _lowerCamelCase : List[str] = vocab_size _lowerCamelCase : List[str] = hidden_size _lowerCamelCase : List[Any] = num_hidden_layers _lowerCamelCase : List[str] = num_attention_heads _lowerCamelCase : Dict = intermediate_size _lowerCamelCase : List[str] = hidden_act _lowerCamelCase : List[Any] = hidden_dropout_prob _lowerCamelCase : Optional[int] = attention_probs_dropout_prob _lowerCamelCase : List[str] = max_position_embeddings _lowerCamelCase : Optional[Any] = type_vocab_size _lowerCamelCase : Dict = type_sequence_label_size _lowerCamelCase : Dict = initializer_range _lowerCamelCase : List[Any] = num_labels _lowerCamelCase : Any = num_choices _lowerCamelCase : List[Any] = scope def _lowercase ( self: List[Any] ): '''simple docstring''' _lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _lowerCamelCase : str = None if self.use_input_mask: _lowerCamelCase : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCamelCase : Optional[int] = None if self.use_token_type_ids: _lowerCamelCase : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) _lowerCamelCase : Dict = None _lowerCamelCase : Union[str, Any] = None _lowerCamelCase : int = None if self.use_labels: _lowerCamelCase : Optional[int] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) _lowerCamelCase : Dict = ids_tensor([self.batch_size] ,self.num_choices ) _lowerCamelCase : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self: Union[str, Any] ): '''simple docstring''' return MraConfig( 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 _lowercase ( self: int ): '''simple docstring''' _lowerCamelCase : str = self.get_config() _lowerCamelCase : Dict = 300 return config def _lowercase ( self: Union[str, Any] ): '''simple docstring''' ( ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ) : int = self.prepare_config_and_inputs() _lowerCamelCase : Tuple = True _lowerCamelCase : int = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _lowerCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _lowercase ( self: List[Any] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: str ,__lowerCAmelCase: Dict ,__lowerCAmelCase: int ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: Tuple ): '''simple docstring''' _lowerCamelCase : Optional[Any] = MraModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[int] = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ) _lowerCamelCase : Union[str, Any] = model(__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ) _lowerCamelCase : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self: Union[str, Any] ,__lowerCAmelCase: Any ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: int ,__lowerCAmelCase: Any ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: List[str] ,): '''simple docstring''' _lowerCamelCase : List[Any] = True _lowerCamelCase : int = MraModel(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : int = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ,encoder_hidden_states=__lowerCAmelCase ,encoder_attention_mask=__lowerCAmelCase ,) _lowerCamelCase : str = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ,encoder_hidden_states=__lowerCAmelCase ,) _lowerCamelCase : Optional[int] = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self: int ,__lowerCAmelCase: Any ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: int ,__lowerCAmelCase: List[str] ): '''simple docstring''' _lowerCamelCase : Tuple = MraForMaskedLM(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Any = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ,labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self: Union[str, Any] ,__lowerCAmelCase: Dict ,__lowerCAmelCase: int ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Optional[int] ): '''simple docstring''' _lowerCamelCase : Dict = MraForQuestionAnswering(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : int = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ,start_positions=__lowerCAmelCase ,end_positions=__lowerCAmelCase ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _lowercase ( self: Tuple ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: str ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Optional[int] ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = self.num_labels _lowerCamelCase : Any = MraForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ,labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowercase ( self: str ,__lowerCAmelCase: Dict ,__lowerCAmelCase: Dict ,__lowerCAmelCase: int ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: str ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = self.num_labels _lowerCamelCase : int = MraForTokenClassification(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ,labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self: Optional[int] ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: Any ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Union[str, Any] ,__lowerCAmelCase: Tuple ): '''simple docstring''' _lowerCamelCase : Optional[Any] = self.num_choices _lowerCamelCase : Optional[Any] = MraForMultipleChoice(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = input_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() _lowerCamelCase : List[str] = token_type_ids.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() _lowerCamelCase : List[str] = input_mask.unsqueeze(1 ).expand(-1 ,self.num_choices ,-1 ).contiguous() _lowerCamelCase : List[Any] = model( __lowerCAmelCase ,attention_mask=__lowerCAmelCase ,token_type_ids=__lowerCAmelCase ,labels=__lowerCAmelCase ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowercase ( self: Optional[Any] ): '''simple docstring''' _lowerCamelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ) : Any = config_and_inputs _lowerCamelCase : Union[str, Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class A_ ( _a , unittest.TestCase ): lowerCAmelCase__ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = () def _lowercase ( self: Dict ): '''simple docstring''' _lowerCamelCase : str = MraModelTester(self ) _lowerCamelCase : List[str] = ConfigTester(self ,config_class=__lowerCAmelCase ,hidden_size=37 ) def _lowercase ( self: Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def _lowercase ( self: Dict ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def _lowercase ( self: Union[str, Any] ): '''simple docstring''' _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _lowerCamelCase : Dict = type self.model_tester.create_and_check_model(*__lowerCAmelCase ) def _lowercase ( self: Union[str, Any] ): '''simple docstring''' _lowerCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase ) def _lowercase ( self: int ): '''simple docstring''' _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowerCAmelCase ) def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase ) def _lowercase ( self: Dict ): '''simple docstring''' _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCAmelCase ) def _lowercase ( self: List[Any] ): '''simple docstring''' _lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase ) @slow def _lowercase ( self: Tuple ): '''simple docstring''' for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Dict = MraModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) @unittest.skip(reason="MRA does not output attentions" ) def _lowercase ( self: str ): '''simple docstring''' return @require_torch class A_ ( unittest.TestCase ): @slow def _lowercase ( self: Any ): '''simple docstring''' _lowerCamelCase : Dict = MraModel.from_pretrained("uw-madison/mra-base-512-4" ) _lowerCamelCase : List[Any] = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): _lowerCamelCase : List[str] = model(__lowerCAmelCase )[0] _lowerCamelCase : str = torch.Size((1, 256, 768) ) self.assertEqual(output.shape ,__lowerCAmelCase ) _lowerCamelCase : List[Any] = torch.tensor( [[[-0.01_40, 0.08_30, -0.03_81], [0.15_46, 0.14_02, 0.02_20], [0.11_62, 0.08_51, 0.01_65]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,__lowerCAmelCase ,atol=1e-4 ) ) @slow def _lowercase ( self: Optional[int] ): '''simple docstring''' _lowerCamelCase : List[Any] = MraForMaskedLM.from_pretrained("uw-madison/mra-base-512-4" ) _lowerCamelCase : List[str] = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): _lowerCamelCase : Dict = model(__lowerCAmelCase )[0] _lowerCamelCase : Optional[Any] = 50_265 _lowerCamelCase : Dict = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape ,__lowerCAmelCase ) _lowerCamelCase : Optional[int] = torch.tensor( [[[9.25_95, -3.60_38, 11.88_19], [9.38_69, -3.26_93, 11.09_56], [11.85_24, -3.49_38, 13.12_10]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,__lowerCAmelCase ,atol=1e-4 ) ) @slow def _lowercase ( self: Dict ): '''simple docstring''' _lowerCamelCase : Any = MraForMaskedLM.from_pretrained("uw-madison/mra-base-4096-8-d3" ) _lowerCamelCase : str = torch.arange(4_096 ).unsqueeze(0 ) with torch.no_grad(): _lowerCamelCase : Any = model(__lowerCAmelCase )[0] _lowerCamelCase : Any = 50_265 _lowerCamelCase : Dict = torch.Size((1, 4_096, vocab_size) ) self.assertEqual(output.shape ,__lowerCAmelCase ) _lowerCamelCase : int = torch.tensor( [[[5.47_89, -2.35_64, 7.50_64], [7.90_67, -1.33_69, 9.96_68], [9.07_12, -1.81_06, 7.03_80]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,__lowerCAmelCase ,atol=1e-4 ) )
46
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : List[str] = logging.get_logger(__name__) _lowerCAmelCase : List[str] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class A_ ( _a ): lowerCAmelCase__ = 'vivit' def __init__( self: List[Any] ,__lowerCAmelCase: int=224 ,__lowerCAmelCase: Any=32 ,__lowerCAmelCase: str=[2, 16, 16] ,__lowerCAmelCase: Optional[Any]=3 ,__lowerCAmelCase: List[str]=768 ,__lowerCAmelCase: List[Any]=12 ,__lowerCAmelCase: Optional[int]=12 ,__lowerCAmelCase: Optional[Any]=3_072 ,__lowerCAmelCase: Any="gelu_fast" ,__lowerCAmelCase: Tuple=0.0 ,__lowerCAmelCase: Any=0.0 ,__lowerCAmelCase: Union[str, Any]=0.02 ,__lowerCAmelCase: List[str]=1e-06 ,__lowerCAmelCase: Optional[Any]=True ,**__lowerCAmelCase: Optional[int] ,): '''simple docstring''' _lowerCamelCase : Any = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : Union[str, Any] = num_attention_heads _lowerCamelCase : Any = intermediate_size _lowerCamelCase : Tuple = hidden_act _lowerCamelCase : Tuple = hidden_dropout_prob _lowerCamelCase : Optional[Any] = attention_probs_dropout_prob _lowerCamelCase : List[Any] = initializer_range _lowerCamelCase : int = layer_norm_eps _lowerCamelCase : Tuple = image_size _lowerCamelCase : Dict = num_frames _lowerCamelCase : Optional[int] = tubelet_size _lowerCamelCase : int = num_channels _lowerCamelCase : List[str] = qkv_bias super().__init__(**__lowerCAmelCase )
46
1
import numpy as np def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = int(np.ceil((x_end - xa) / h ) ) SCREAMING_SNAKE_CASE_ = np.zeros((n + 1,) ) SCREAMING_SNAKE_CASE_ = ya SCREAMING_SNAKE_CASE_ = xa for k in range(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = f(__lowerCamelCase, y[k] ) SCREAMING_SNAKE_CASE_ = f(x + 0.5 * h, y[k] + 0.5 * h * ka ) SCREAMING_SNAKE_CASE_ = f(x + 0.5 * h, y[k] + 0.5 * h * ka ) SCREAMING_SNAKE_CASE_ = f(x + h, y[k] + h * ka ) SCREAMING_SNAKE_CASE_ = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
597
import socket def A__ ( ): SCREAMING_SNAKE_CASE_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM ) SCREAMING_SNAKE_CASE_ = socket.gethostname() SCREAMING_SNAKE_CASE_ = 1_23_12 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: SCREAMING_SNAKE_CASE_ = sock.recv(10_24 ) if not data: break out_file.write(__lowerCamelCase ) print('''Successfully received the file''' ) sock.close() print('''Connection closed''' ) if __name__ == "__main__": main()
597
1
"""simple docstring""" import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch UpperCamelCase__ = logging.get_logger(__name__) class a : def __init__( self , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_=None , UpperCamelCase_=None ): if not conversation_id: UpperCAmelCase__ : Any = uuid.uuida() if past_user_inputs is None: UpperCAmelCase__ : Union[str, Any] = [] if generated_responses is None: UpperCAmelCase__ : List[str] = [] UpperCAmelCase__ : uuid.UUID = conversation_id UpperCAmelCase__ : List[str] = past_user_inputs UpperCAmelCase__ : List[str] = generated_responses UpperCAmelCase__ : Optional[str] = text def __eq__( self , UpperCamelCase_ ): if not isinstance(__lowercase , __lowercase ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_ = False ): if self.new_user_input: if overwrite: logger.warning( F'''User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten ''' F'''with: \"{text}\".''' ) UpperCAmelCase__ : Optional[int] = text else: logger.warning( F'''User input added while unprocessed input was existing: \"{self.new_user_input}\" new input ''' F'''ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input''' ) else: UpperCAmelCase__ : Any = text def __snake_case ( self ): if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) UpperCAmelCase__ : int = None def __snake_case ( self , UpperCamelCase_ ): self.generated_responses.append(__lowercase ) def __snake_case ( self ): for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self ): UpperCAmelCase__ : List[str] = F'''Conversation id: {self.uuid} \n''' for is_user, text in self.iter_texts(): UpperCAmelCase__ : Union[str, Any] = '''user''' if is_user else '''bot''' output += F'''{name} >> {text} \n''' return output @add_end_docstrings( __lowerCamelCase , r""" min_length_for_response (`int`, *optional*, defaults to 32): The minimum length (in number of tokens) for a response. minimum_tokens (`int`, *optional*, defaults to 10): The minimum length of tokens to leave for a response. """ , ) class a ( __lowerCamelCase ): def __init__( self , *UpperCamelCase_ , **UpperCamelCase_ ): super().__init__(*__lowercase , **__lowercase ) if self.tokenizer.pad_token_id is None: UpperCAmelCase__ : int = self.tokenizer.eos_token def __snake_case ( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=None , **UpperCamelCase_ ): UpperCAmelCase__ : Any = {} UpperCAmelCase__ : Any = {} UpperCAmelCase__ : Tuple = {} if min_length_for_response is not None: UpperCAmelCase__ : Dict = min_length_for_response if minimum_tokens is not None: UpperCAmelCase__ : Dict = minimum_tokens if "max_length" in generate_kwargs: UpperCAmelCase__ : Any = generate_kwargs['''max_length'''] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: UpperCAmelCase__ : List[Any] = clean_up_tokenization_spaces if generate_kwargs: forward_params.update(__lowercase ) return preprocess_params, forward_params, postprocess_params def __call__( self , UpperCamelCase_ , UpperCamelCase_=0 , **UpperCamelCase_ ): UpperCAmelCase__ : Optional[int] = super().__call__(__lowercase , num_workers=__lowercase , **__lowercase ) if isinstance(__lowercase , __lowercase ) and len(__lowercase ) == 1: return outputs[0] return outputs def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_=32 ): if not isinstance(__lowercase , __lowercase ): raise ValueError('ConversationalPipeline, expects Conversation as inputs' ) if conversation.new_user_input is None: raise ValueError( F'''Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. ''' 'Add user inputs with the conversation\'s `add_user_input` method' ) if hasattr(self.tokenizer , '_build_conversation_input_ids' ): UpperCAmelCase__ : Tuple = self.tokenizer._build_conversation_input_ids(__lowercase ) else: # If the tokenizer cannot handle conversations, we default to only the old version UpperCAmelCase__ : Tuple = self._legacy_parse_and_tokenize(__lowercase ) if self.framework == "pt": UpperCAmelCase__ : str = torch.LongTensor([input_ids] ) elif self.framework == "tf": UpperCAmelCase__ : Tuple = tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_=10 , **UpperCamelCase_ ): UpperCAmelCase__ : List[Any] = generate_kwargs.get('max_length' , self.model.config.max_length ) UpperCAmelCase__ : Dict = model_inputs['''input_ids'''].shape[1] if max_length - minimum_tokens < n: logger.warning(F'''Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})''' ) UpperCAmelCase__ : List[Any] = max_length - minimum_tokens UpperCAmelCase__ : Tuple = model_inputs['''input_ids'''][:, -trim:] if "attention_mask" in model_inputs: UpperCAmelCase__ : Union[str, Any] = model_inputs['''attention_mask'''][:, -trim:] UpperCAmelCase__ : List[Any] = model_inputs.pop('conversation' ) UpperCAmelCase__ : List[str] = max_length UpperCAmelCase__ : str = self.model.generate(**__lowercase , **__lowercase ) if self.model.config.is_encoder_decoder: UpperCAmelCase__ : Dict = 1 else: UpperCAmelCase__ : str = n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def __snake_case ( self , UpperCamelCase_ , UpperCamelCase_=True ): UpperCAmelCase__ : Any = model_outputs['''output_ids'''] UpperCAmelCase__ : Tuple = self.tokenizer.decode( output_ids[0] , skip_special_tokens=__lowercase , clean_up_tokenization_spaces=__lowercase , ) UpperCAmelCase__ : Optional[Any] = model_outputs['''conversation'''] conversation.mark_processed() conversation.append_response(__lowercase ) return conversation def __snake_case ( self , UpperCamelCase_ ): UpperCAmelCase__ : Any = self.tokenizer.eos_token_id UpperCAmelCase__ : List[str] = [] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(__lowercase , add_special_tokens=__lowercase ) ) if len(__lowercase ) > self.tokenizer.model_max_length: UpperCAmelCase__ : Tuple = input_ids[-self.tokenizer.model_max_length :] return input_ids
110
import unittest import numpy as np from transformers import AlbertConfig, 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.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class a ( unittest.TestCase ): def __init__( self :List[str] ,__lowercase :Any ,__lowercase :Optional[Any]=1_3 ,__lowercase :Optional[Any]=7 ,__lowercase :Union[str, Any]=True ,__lowercase :Optional[int]=True ,__lowercase :Dict=True ,__lowercase :int=True ,__lowercase :List[str]=9_9 ,__lowercase :Optional[Any]=3_2 ,__lowercase :Dict=5 ,__lowercase :List[str]=4 ,__lowercase :Dict=3_7 ,__lowercase :Dict="gelu" ,__lowercase :Any=0.1 ,__lowercase :Any=0.1 ,__lowercase :int=5_1_2 ,__lowercase :List[str]=1_6 ,__lowercase :List[Any]=2 ,__lowercase :List[str]=0.02 ,__lowercase :Optional[int]=4 ,): snake_case__ : Union[str, Any] = parent snake_case__ : List[Any] = batch_size snake_case__ : Optional[int] = seq_length snake_case__ : Optional[Any] = is_training snake_case__ : Optional[Any] = use_attention_mask snake_case__ : Tuple = use_token_type_ids snake_case__ : str = use_labels snake_case__ : Union[str, Any] = vocab_size snake_case__ : List[Any] = hidden_size snake_case__ : List[str] = num_hidden_layers snake_case__ : Optional[Any] = num_attention_heads snake_case__ : Optional[int] = intermediate_size snake_case__ : Dict = hidden_act snake_case__ : str = hidden_dropout_prob snake_case__ : str = attention_probs_dropout_prob snake_case__ : List[Any] = max_position_embeddings snake_case__ : List[str] = type_vocab_size snake_case__ : Union[str, Any] = type_sequence_label_size snake_case__ : Tuple = initializer_range snake_case__ : Tuple = num_choices def __lowerCamelCase ( self :Union[str, Any] ): snake_case__ : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) snake_case__ : Optional[Any] = None if self.use_attention_mask: snake_case__ : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) snake_case__ : str = None if self.use_token_type_ids: snake_case__ : Dict = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) snake_case__ : Any = AlbertConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,is_decoder=__lowercase ,initializer_range=self.initializer_range ,) return config, input_ids, token_type_ids, attention_mask def __lowerCamelCase ( self :Any ): snake_case__ : Any = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ , snake_case__ : Any = config_and_inputs snake_case__ : Dict = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class a ( __lowerCamelCase , unittest.TestCase ): __lowerCAmelCase : List[str] = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def __lowerCamelCase ( self :Optional[Any] ): snake_case__ : Optional[int] = FlaxAlbertModelTester(self ) @slow def __lowerCamelCase ( self :List[str] ): for model_class_name in self.all_model_classes: snake_case__ : Any = model_class_name.from_pretrained('''albert-base-v2''' ) snake_case__ : str = model(np.ones((1, 1) ) ) self.assertIsNotNone(__lowercase ) @require_flax class a ( unittest.TestCase ): @slow def __lowerCamelCase ( self :str ): snake_case__ : str = FlaxAlbertModel.from_pretrained('''albert-base-v2''' ) snake_case__ : int = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) snake_case__ : Optional[Any] = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) snake_case__ : List[str] = model(__lowercase ,attention_mask=__lowercase )[0] snake_case__ : Optional[Any] = (1, 1_1, 7_6_8) self.assertEqual(output.shape ,__lowercase ) snake_case__ : List[str] = np.array( [[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,__lowercase ,atol=1e-4 ) )
252
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : List[Any] = logging.get_logger(__name__) _lowerCamelCase : Dict = { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/config.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/config.json", } class __snake_case (_a ): lowerCAmelCase__ = "xlnet" lowerCAmelCase__ = ["mems"] lowerCAmelCase__ = { "n_token": "vocab_size", # Backward compatibility "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Any , _UpperCAmelCase : Dict=3_2000 , _UpperCAmelCase : Optional[Any]=1024 , _UpperCAmelCase : Optional[Any]=24 , _UpperCAmelCase : str=16 , _UpperCAmelCase : Dict=4096 , _UpperCAmelCase : Any="gelu" , _UpperCAmelCase : Union[str, Any]=True , _UpperCAmelCase : Dict="bi" , _UpperCAmelCase : List[Any]=0.02 , _UpperCAmelCase : Optional[Any]=1E-12 , _UpperCAmelCase : Dict=0.1 , _UpperCAmelCase : int=512 , _UpperCAmelCase : Tuple=None , _UpperCAmelCase : List[Any]=True , _UpperCAmelCase : Dict=False , _UpperCAmelCase : Any=False , _UpperCAmelCase : str=-1 , _UpperCAmelCase : Optional[Any]=False , _UpperCAmelCase : str="last" , _UpperCAmelCase : Dict=True , _UpperCAmelCase : Dict="tanh" , _UpperCAmelCase : int=0.1 , _UpperCAmelCase : Tuple=5 , _UpperCAmelCase : int=5 , _UpperCAmelCase : Any=5 , _UpperCAmelCase : Optional[int]=1 , _UpperCAmelCase : Any=2 , **_UpperCAmelCase : List[Any] , ) -> Optional[int]: '''simple docstring''' _lowerCAmelCase : Any = vocab_size _lowerCAmelCase : Dict = d_model _lowerCAmelCase : Tuple = n_layer _lowerCAmelCase : Any = n_head if d_model % n_head != 0: raise ValueError(f"'d_model % n_head' ({d_model % n_head}) should be equal to 0" ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( f"`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})" ) _lowerCAmelCase : Optional[Any] = d_model // n_head _lowerCAmelCase : Union[str, Any] = ff_activation _lowerCAmelCase : str = d_inner _lowerCAmelCase : Tuple = untie_r _lowerCAmelCase : Tuple = attn_type _lowerCAmelCase : Tuple = initializer_range _lowerCAmelCase : Union[str, Any] = layer_norm_eps _lowerCAmelCase : Any = dropout _lowerCAmelCase : Dict = mem_len _lowerCAmelCase : Optional[Any] = reuse_len _lowerCAmelCase : List[Any] = bi_data _lowerCAmelCase : str = clamp_len _lowerCAmelCase : Union[str, Any] = same_length _lowerCAmelCase : Tuple = summary_type _lowerCAmelCase : str = summary_use_proj _lowerCAmelCase : int = summary_activation _lowerCAmelCase : Optional[Any] = summary_last_dropout _lowerCAmelCase : int = start_n_top _lowerCAmelCase : Tuple = end_n_top _lowerCAmelCase : Optional[Any] = bos_token_id _lowerCAmelCase : int = pad_token_id _lowerCAmelCase : Tuple = eos_token_id if "use_cache" in kwargs: warnings.warn( """The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`""" """ instead.""" , _UpperCAmelCase , ) _lowerCAmelCase : Union[str, Any] = kwargs["""use_cache"""] _lowerCAmelCase : Optional[Any] = use_mems_eval _lowerCAmelCase : Tuple = use_mems_train super().__init__(pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , **_UpperCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : List[str] ) -> int: '''simple docstring''' 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 SCREAMING_SNAKE_CASE ( self : str , _UpperCAmelCase : str ) -> List[Any]: '''simple docstring''' raise NotImplementedError( f"The model {self.model_type} is one of the few models that has no sequence length limit." )
196
import argparse from typing import List import evaluate import numpy as np import torch from datasets import DatasetDict, load_dataset # New Code # # We'll be using StratifiedKFold for this example from sklearn.model_selection import StratifiedKFold from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to perform Cross Validation, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## _lowerCamelCase : Any = 1_6 _lowerCamelCase : Tuple = 3_2 def _UpperCAmelCase (UpperCamelCase_ : Accelerator , UpperCamelCase_ : DatasetDict , UpperCamelCase_ : List[int] , UpperCamelCase_ : List[int] , UpperCamelCase_ : int = 16 ): '''simple docstring''' _lowerCAmelCase : Any = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _lowerCAmelCase : int = DatasetDict( { """train""": dataset["""train"""].select(UpperCamelCase_ ), """validation""": dataset["""train"""].select(UpperCamelCase_ ), """test""": dataset["""validation"""], } ) def tokenize_function(UpperCamelCase_ : str ): # max_length=None => use the model max length (it's actually the default) _lowerCAmelCase : List[Any] = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _lowerCAmelCase : List[str] = datasets.map( UpperCamelCase_ , batched=UpperCamelCase_ , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _lowerCAmelCase : Optional[Any] = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(UpperCamelCase_ : Optional[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. _lowerCAmelCase : List[str] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _lowerCAmelCase : Optional[Any] = 16 elif accelerator.mixed_precision != "no": _lowerCAmelCase : int = 8 else: _lowerCAmelCase : Dict = None return tokenizer.pad( UpperCamelCase_ , padding="""longest""" , max_length=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_tensors="""pt""" , ) # Instantiate dataloaders. _lowerCAmelCase : Optional[Any] = DataLoader( tokenized_datasets["""train"""] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ ) _lowerCAmelCase : Tuple = DataLoader( tokenized_datasets["""validation"""] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ ) _lowerCAmelCase : List[str] = DataLoader( tokenized_datasets["""test"""] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ ) return train_dataloader, eval_dataloader, test_dataloader def _UpperCAmelCase (UpperCamelCase_ : Any , UpperCamelCase_ : Optional[int] ): '''simple docstring''' # New Code # _lowerCAmelCase : Dict = [] # Download the dataset _lowerCAmelCase : Optional[int] = load_dataset("""glue""" , """mrpc""" ) # Create our splits _lowerCAmelCase : Any = StratifiedKFold(n_splits=int(args.num_folds ) ) # Initialize accelerator _lowerCAmelCase : int = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _lowerCAmelCase : List[str] = config["""lr"""] _lowerCAmelCase : Any = int(config["""num_epochs"""] ) _lowerCAmelCase : Dict = int(config["""seed"""] ) _lowerCAmelCase : Union[str, Any] = int(config["""batch_size"""] ) _lowerCAmelCase : Optional[Any] = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _lowerCAmelCase : Optional[Any] = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _lowerCAmelCase : Optional[Any] = batch_size // MAX_GPU_BATCH_SIZE _lowerCAmelCase : int = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase_ ) # New Code # # Create our folds: _lowerCAmelCase : Optional[int] = kfold.split(np.zeros(datasets["""train"""].num_rows ) , datasets["""train"""]["""label"""] ) _lowerCAmelCase : Any = [] # Iterate over them for i, (train_idxs, valid_idxs) in enumerate(UpperCamelCase_ ): _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[str] = get_fold_dataloaders( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _lowerCAmelCase : int = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=UpperCamelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _lowerCAmelCase : Union[str, Any] = model.to(accelerator.device ) # Instantiate optimizer _lowerCAmelCase : Any = AdamW(params=model.parameters() , lr=UpperCamelCase_ ) # Instantiate scheduler _lowerCAmelCase : Tuple = get_linear_schedule_with_warmup( optimizer=UpperCamelCase_ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase_ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase : List[str] = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Now we train the model for epoch in range(UpperCamelCase_ ): model.train() for step, batch in enumerate(UpperCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _lowerCAmelCase : Tuple = model(**UpperCamelCase_ ) _lowerCAmelCase : Optional[int] = outputs.loss _lowerCAmelCase : Optional[int] = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _lowerCAmelCase : List[Any] = model(**UpperCamelCase_ ) _lowerCAmelCase : List[Any] = outputs.logits.argmax(dim=-1 ) _lowerCAmelCase , _lowerCAmelCase : Any = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=UpperCamelCase_ , references=UpperCamelCase_ , ) _lowerCAmelCase : List[Any] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , UpperCamelCase_ ) # New Code # # We also run predictions on the test set at the very end _lowerCAmelCase : Dict = [] for step, batch in enumerate(UpperCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _lowerCAmelCase : Dict = model(**UpperCamelCase_ ) _lowerCAmelCase : List[Any] = outputs.logits _lowerCAmelCase , _lowerCAmelCase : Optional[int] = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) fold_predictions.append(predictions.cpu() ) if i == 0: # We need all of the test predictions test_references.append(references.cpu() ) # Use accelerator.print to print only on the main process. test_predictions.append(torch.cat(UpperCamelCase_ , dim=0 ) ) # We now need to release all our memory and get rid of the current model, optimizer, etc accelerator.free_memory() # New Code # # Finally we check the accuracy of our folded results: _lowerCAmelCase : Tuple = torch.cat(UpperCamelCase_ , dim=0 ) _lowerCAmelCase : Tuple = torch.stack(UpperCamelCase_ , dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 ) _lowerCAmelCase : Union[str, Any] = metric.compute(predictions=UpperCamelCase_ , references=UpperCamelCase_ ) accelerator.print("""Average test metrics from all folds:""" , UpperCamelCase_ ) def _UpperCAmelCase (): '''simple docstring''' _lowerCAmelCase : Optional[int] = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=UpperCamelCase_ , default=UpperCamelCase_ , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) # New Code # parser.add_argument("""--num_folds""" , type=UpperCamelCase_ , default=3 , help="""The number of splits to perform across the dataset""" ) _lowerCAmelCase : Optional[Any] = parser.parse_args() _lowerCAmelCase : List[Any] = {"""lr""": 2E-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(UpperCamelCase_ , UpperCamelCase_ ) if __name__ == "__main__": main()
196
1
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class SCREAMING_SNAKE_CASE ( unittest.TestCase ): def SCREAMING_SNAKE_CASE ( self : str ) -> Dict: a_ : Union[str, Any] = inspect.getfile(accelerate.test_utils ) a_ : str = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) a_ : Any = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) a_ : Tuple = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Tuple: print(f'Found {torch.cuda.device_count()} devices.' ) a_ : List[str] = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]: print(f'Found {torch.cuda.device_count()} devices.' ) a_ : List[Any] = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', self.operation_file_path] print(f'Command: {cmd}' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def SCREAMING_SNAKE_CASE ( self : str ) -> Optional[int]: a_ : Optional[int] = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) @require_multi_gpu def SCREAMING_SNAKE_CASE ( self : Dict ) -> Optional[Any]: print(f'Found {torch.cuda.device_count()} devices, using 2 devices only' ) a_ : Optional[Any] = ['''torchrun''', f'--nproc_per_node={torch.cuda.device_count()}', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(__SCREAMING_SNAKE_CASE , env=os.environ.copy() ) if __name__ == "__main__": __lowerCAmelCase = Accelerator() __lowerCAmelCase = (accelerator.state.process_index + 2, 10) __lowerCAmelCase = torch.randint(0, 10, shape).to(accelerator.device) __lowerCAmelCase = '' __lowerCAmelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." __lowerCAmelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." __lowerCAmelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
466
'''simple docstring''' # This script creates a super tiny model that is useful inside tests, when we just want to test that # the machinery works, without needing to the check the quality of the outcomes. # # This version creates a tiny model through reduction of a normal pre-trained model, but keeping the # full vocab, merges file, and thus also resulting in a larger model due to a large vocab size. # This gives ~3MB in total for all files. # # If you want a 50 times smaller than this see `fsmt-make-super-tiny-model.py`, which is slightly more complicated # # # It will be used then as "stas/tiny-wmt19-en-de" # Build from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration __lowerCAmelCase = 'facebook/wmt19-en-de' __lowerCAmelCase = FSMTTokenizer.from_pretrained(mname) # get the correct vocab sizes, etc. from the master model __lowerCAmelCase = FSMTConfig.from_pretrained(mname) config.update( dict( d_model=4, encoder_layers=1, decoder_layers=1, encoder_ffn_dim=4, decoder_ffn_dim=4, encoder_attention_heads=1, decoder_attention_heads=1, ) ) __lowerCAmelCase = FSMTForConditionalGeneration(config) print(F"""num of params {tiny_model.num_parameters()}""") # Test __lowerCAmelCase = tokenizer(['Making tiny model'], return_tensors='pt') __lowerCAmelCase = tiny_model(**batch) print('test output:', len(outputs.logits[0])) # Save __lowerCAmelCase = 'tiny-wmt19-en-de' tiny_model.half() # makes it smaller tiny_model.save_pretrained(mname_tiny) tokenizer.save_pretrained(mname_tiny) print(F"""Generated {mname_tiny}""") # Upload # transformers-cli upload tiny-wmt19-en-de
466
1
"""simple docstring""" from math import pow, sqrt def _snake_case ( *lowercase__ ): _lowerCamelCase : Dict = len(lowercase__ ) > 0 and all(value > 0.0 for value in values ) return result def _snake_case ( lowercase__ , lowercase__ ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(lowercase__ , lowercase__ ) else ValueError('Input Error: Molar mass values must greater than 0.' ) ) def _snake_case ( lowercase__ , lowercase__ , lowercase__ ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(lowercase__ , lowercase__ , lowercase__ ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def _snake_case ( lowercase__ , lowercase__ , lowercase__ ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(lowercase__ , lowercase__ , lowercase__ ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def _snake_case ( lowercase__ , lowercase__ , lowercase__ ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(lowercase__ , lowercase__ , lowercase__ ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) ) def _snake_case ( lowercase__ , lowercase__ , lowercase__ ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(lowercase__ , lowercase__ , lowercase__ ) else ValueError( 'Input Error: Molar mass and effusion rate values must greater than 0.' ) )
712
"""simple docstring""" def _snake_case ( lowercase__ ): _lowerCamelCase : Optional[int] = int(lowercase__ ) if decimal in (0, 1): # Exit cases for the recursion return str(lowercase__ ) _lowerCamelCase, _lowerCamelCase : Dict = divmod(lowercase__ , 2 ) return binary_recursive(lowercase__ ) + str(lowercase__ ) def _snake_case ( lowercase__ ): _lowerCamelCase : List[Any] = str(lowercase__ ).strip() if not number: raise ValueError('No input value was provided' ) _lowerCamelCase : str = '-' if number.startswith('-' ) else '' _lowerCamelCase : Union[str, Any] = number.lstrip('-' ) if not number.isnumeric(): raise ValueError('Input value is not an integer' ) return f'''{negative}0b{binary_recursive(int(lowercase__ ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
492
0
import math import sys def _SCREAMING_SNAKE_CASE ( snake_case ) -> int: if number != int(snake_case ): raise ValueError("""the value of input must be a natural number""" ) if number < 0: raise ValueError("""the value of input must not be a negative number""" ) if number == 0: return 1 _UpperCAmelCase = [-1] * (number + 1) _UpperCAmelCase = 0 for i in range(1 , number + 1 ): _UpperCAmelCase = sys.maxsize _UpperCAmelCase = int(math.sqrt(snake_case ) ) for j in range(1 , root + 1 ): _UpperCAmelCase = 1 + answers[i - (j**2)] _UpperCAmelCase = min(snake_case , snake_case ) _UpperCAmelCase = answer return answers[number] if __name__ == "__main__": import doctest doctest.testmod()
518
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys a = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
518
1
"""simple docstring""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo __lowerCamelCase = "\\n@misc{wu2016googles,\n title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n" __lowerCamelCase = "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n" __lowerCamelCase = "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n 'google_bleu': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n ... 'heed', 'the', 'cat', 'commands']\n >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n ... 'of', 'the', 'cat']\n\n >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n ... 'interested', 'in', 'world', 'history']\n >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n ... 'because', 'he', 'read', 'the', 'book']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric(\"google_bleu\")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results[\"google_bleu\"], 2))\n 0.4\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowercase ( datasets.Metric ): def lowerCAmelCase__ ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ), } ) , ) def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = 1 , UpperCamelCase_ = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=UpperCamelCase_ , hypotheses=UpperCamelCase_ , min_len=UpperCamelCase_ , max_len=UpperCamelCase_ ) }
713
"""simple docstring""" import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class _lowercase ( __UpperCAmelCase , unittest.TestCase ): _lowerCamelCase = FunnelTokenizer _lowerCamelCase = FunnelTokenizerFast _lowerCamelCase = True _lowerCamelCase = True def lowerCAmelCase__ ( self ): super().setUp() __magic_name__ = [ '''<unk>''', '''<cls>''', '''<sep>''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __magic_name__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def lowerCAmelCase__ ( self , **UpperCamelCase_ ): return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def lowerCAmelCase__ ( self , **UpperCamelCase_ ): return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def lowerCAmelCase__ ( self , UpperCamelCase_ ): __magic_name__ = '''UNwant\u00E9d,running''' __magic_name__ = '''unwanted, running''' return input_text, output_text def lowerCAmelCase__ ( self ): __magic_name__ = self.tokenizer_class(self.vocab_file ) __magic_name__ = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(UpperCamelCase_ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) , [7, 4, 5, 10, 8, 9] ) def lowerCAmelCase__ ( self ): __magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase_ ) for tokenizer in tokenizers: __magic_name__ = tokenizer('''UNwant\u00E9d,running''' ) __magic_name__ = len(inputs['''input_ids'''] ) - 1 self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len ) __magic_name__ = tokenizer('''UNwant\u00E9d,running''' , '''UNwant\u00E9d,running''' ) self.assertListEqual(inputs['''token_type_ids'''] , [2] + [0] * sentence_len + [1] * sentence_len )
190
0
'''simple docstring''' import argparse import shutil import time from json import JSONDecodeError from logging import getLogger from pathlib import Path from typing import Dict, List import torch from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoModelForSeqaSeqLM, AutoTokenizer from utils import ( SeqaSeqDataset, calculate_bleu, calculate_rouge, chunks, lmap, load_json, parse_numeric_n_bool_cl_kwargs, save_json, use_task_specific_params, write_txt_file, ) lowerCAmelCase : Union[str, Any] =getLogger(__name__) def UpperCAmelCase_ ( __lowerCamelCase : Union[str, Any] ,__lowerCamelCase : Dict ,__lowerCamelCase : int ,__lowerCamelCase : Union[str, Any] = 8 ,__lowerCamelCase : Union[str, Any] = 10_24 ,__lowerCamelCase : Optional[Any]="val" ,__lowerCamelCase : int=None ,__lowerCamelCase : Dict=False ,__lowerCamelCase : int="summarization" ,__lowerCamelCase : Tuple=None ,__lowerCamelCase : str=1 ,__lowerCamelCase : Dict = None ,__lowerCamelCase : Tuple="" ,**__lowerCamelCase : Union[str, Any] ,): lowercase_ :Any = str(a__ ) assert local_rank is not None torch.distributed.init_process_group(backend="nccl" ,rank=a__ ) lowercase_ :Tuple = Path(a__ ) lowercase_ :Optional[Any] = save_dir.joinpath(F'rank_{local_rank}_output.json' ) torch.cuda.set_device(a__ ) lowercase_ :List[str] = AutoModelForSeqaSeqLM.from_pretrained(a__ ).cuda() if fpaa: lowercase_ :Optional[Any] = model.half() # determine if we need to increase num_beams use_task_specific_params(a__ ,a__ ) # update config with task specific params lowercase_ :List[str] = generate_kwargs.pop("num_beams" ,model.config.num_beams ) # AttributeError risk? if num_return_sequences > num_beams: lowercase_ :Tuple = num_return_sequences lowercase_ :List[Any] = AutoTokenizer.from_pretrained(a__ ) logger.info(F'Inferred tokenizer type: {tokenizer.__class__}' ) # if this is wrong, check config.model_type. if max_source_length is None: lowercase_ :str = tokenizer.model_max_length if prefix is None: lowercase_ :str = prefix or getattr(model.config ,"prefix" ,"" ) or """""" lowercase_ :Optional[int] = SeqaSeqDataset( a__ ,a__ ,a__ ,max_target_length=10_24 ,type_path=a__ ,n_obs=a__ ,prefix=a__ ,**a__ ,) # I set shuffle=True for a more accurate progress bar. # If all the longest samples are first, the prog bar estimate is too high at the beginning. lowercase_ :Optional[int] = ds.make_sortish_sampler(a__ ,distributed=a__ ,add_extra_examples=a__ ,shuffle=a__ ) lowercase_ :Dict = DataLoader(a__ ,sampler=a__ ,batch_size=a__ ,collate_fn=ds.collate_fn ) lowercase_ :Dict = [] for batch in tqdm(a__ ): lowercase_ :Any = model.generate( input_ids=batch["input_ids"].to(model.device ) ,attention_mask=batch["attention_mask"].to(model.device ) ,num_return_sequences=a__ ,num_beams=a__ ,**a__ ,) lowercase_ :List[str] = tokenizer.batch_decode(a__ ,skip_special_tokens=a__ ,clean_up_tokenization_spaces=a__ ) lowercase_ :Union[str, Any] = batch["""ids"""] if num_return_sequences > 1: lowercase_ :int = chunks(a__ ,a__ ) # batch size chunks, each of size num_return_seq for i, pred in enumerate(a__ ): results.append({"pred": pred, "id": ids[i].item()} ) save_json(a__ ,a__ ) return results, sampler.num_replicas def UpperCAmelCase_ ( ): lowercase_ :int = argparse.ArgumentParser( epilog="Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate" ) parser.add_argument("--data_dir" ,type=a__ ,help="like cnn_dm/test.source" ) parser.add_argument( "--model_name" ,type=a__ ,help="like facebook/bart-large-cnn,t5-base, etc." ,default="sshleifer/distilbart-xsum-12-3" ,) parser.add_argument("--save_dir" ,type=a__ ,help="where to save" ,default="tmp_gen" ) parser.add_argument("--max_source_length" ,type=a__ ,default=a__ ) parser.add_argument( "--type_path" ,type=a__ ,default="test" ,help="which subset to evaluate typically train/val/test" ) parser.add_argument("--task" ,type=a__ ,default="summarization" ,help="used for task_specific_params + metrics" ) parser.add_argument("--bs" ,type=a__ ,default=8 ,required=a__ ,help="batch size" ) parser.add_argument( "--local_rank" ,type=a__ ,default=-1 ,required=a__ ,help="should be passed by distributed.launch" ) parser.add_argument( "--n_obs" ,type=a__ ,default=a__ ,required=a__ ,help="How many observations. Defaults to all." ) parser.add_argument( "--num_return_sequences" ,type=a__ ,default=1 ,required=a__ ,help="How many sequences to return" ) parser.add_argument( "--sync_timeout" ,type=a__ ,default=6_00 ,required=a__ ,help="How long should master process wait for other processes to finish." ,) parser.add_argument("--src_lang" ,type=a__ ,default=a__ ,required=a__ ) parser.add_argument("--tgt_lang" ,type=a__ ,default=a__ ,required=a__ ) parser.add_argument( "--prefix" ,type=a__ ,required=a__ ,default=a__ ,help="will be added to the begininng of src examples" ) parser.add_argument("--fp16" ,action="store_true" ) parser.add_argument("--debug" ,action="store_true" ) lowercase_ :Union[str, Any] = time.time() lowercase_ :Optional[Any] = parser.parse_known_args() lowercase_ :int = parse_numeric_n_bool_cl_kwargs(a__ ) if generate_kwargs and args.local_rank <= 0: print(F'parsed the following generate kwargs: {generate_kwargs}' ) lowercase_ :str = Path(args.save_dir + "_tmp" ) Path(a__ ).mkdir(exist_ok=a__ ) # this handles locking. lowercase_ :str = list(json_save_dir.glob("rank_*.json" ) ) if intermediate_files: raise ValueError(F'Found files at {json_save_dir} please move or remove them.' ) # In theory, a node could finish and save before another node hits this. If this happens, we can address later. lowercase_ :Dict = {} if args.src_lang is not None: lowercase_ :Dict = args.src_lang if args.tgt_lang is not None: lowercase_ :str = args.tgt_lang Path(args.save_dir ).mkdir(exist_ok=a__ ) lowercase_ :Tuple = eval_data_dir( args.data_dir ,a__ ,args.model_name ,type_path=args.type_path ,bs=args.bs ,fpaa=args.fpaa ,task=args.task ,local_rank=args.local_rank ,n_obs=args.n_obs ,max_source_length=args.max_source_length ,num_return_sequences=args.num_return_sequences ,prefix=args.prefix ,dataset_kwargs=a__ ,**a__ ,) if args.local_rank <= 0: lowercase_ :List[str] = Path(args.save_dir ) save_dir.mkdir(exist_ok=a__ ) lowercase_ :Tuple = gather_results_from_each_node(a__ ,a__ ,args.sync_timeout ) lowercase_ :str = combine_partial_results(a__ ) if args.num_return_sequences > 1: lowercase_ :str = save_dir.joinpath("pseudolabel_results.json" ) print(F'Saving aggregated results at {save_path}, intermediate in {json_save_dir}/' ) save_json(a__ ,a__ ) return lowercase_ :Any = Path(args.data_dir ).joinpath(args.type_path + ".target" ) with open(a__ ) as f: lowercase_ :Optional[int] = [x.rstrip() for x in f.readlines()][: len(a__ )] # Calculate metrics, save metrics, and save _generations.txt lowercase_ :Any = """translation""" in args.task lowercase_ :Optional[int] = calculate_bleu if calc_bleu else calculate_rouge lowercase_ :Union[str, Any] = """bleu""" if calc_bleu else """rouge""" lowercase_ :Dict = score_fn(a__ ,a__ ) lowercase_ :Optional[Any] = len(a__ ) lowercase_ :Tuple = time.time() - start_time lowercase_ :Optional[int] = round(runtime / metrics["n_obs"] ,4 ) lowercase_ :List[str] = num_replicas # TODO(@stas00): add whatever metadata to metrics lowercase_ :int = save_dir.joinpath(F'{args.type_path}_{metric_name}.json' ) save_json(a__ ,a__ ,indent=a__ ) print(a__ ) write_txt_file(a__ ,save_dir.joinpath(F'{args.type_path}_generations.txt' ) ) if args.debug: write_txt_file(a__ ,save_dir.joinpath(F'{args.type_path}.target' ) ) else: shutil.rmtree(a__ ) def UpperCAmelCase_ ( __lowerCamelCase : Union[str, Any] ): lowercase_ :Union[str, Any] = [] for partial_result in partial_results: records.extend(a__ ) lowercase_ :Any = sorted(a__ ,key=lambda __lowerCamelCase : x["id"] ) lowercase_ :Optional[int] = [x["""pred"""] for x in records] return preds def UpperCAmelCase_ ( __lowerCamelCase : List[str] ,__lowerCamelCase : Dict ,__lowerCamelCase : Optional[int] ): lowercase_ :List[Any] = time.time() logger.info("waiting for all nodes to finish" ) lowercase_ :Optional[int] = None while (time.time() - start_wait) < timeout: lowercase_ :Union[str, Any] = list(save_dir.glob("rank_*.json" ) ) if len(a__ ) < num_replicas: continue try: # make sure all json files are fully saved lowercase_ :Tuple = lmap(a__ ,a__ ) return json_data except JSONDecodeError: continue else: raise TimeoutError("Rank 0 gave up on waiting for other processes" ) # Unreachable if __name__ == "__main__": # Usage for MT: run_generate()
172
from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class A__(a_ ): """simple docstring""" def UpperCamelCase__ ( self ) -> List[str]: a_ : List[Any] = SMALL_MODEL_IDENTIFIER a_ : Optional[int] = """pt""" a_ : Union[str, Any] = """tf""" def UpperCamelCase__ ( self , _lowercase ) -> str: a_ : Union[str, Any] = AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(_lowercase ) def UpperCamelCase__ ( self , _lowercase ) -> List[str]: a_ : int = TFAutoModel.from_pretrained(self.test_model , from_pt=_lowercase ) model_tf.save_pretrained(_lowercase ) def UpperCamelCase__ ( self ) -> Optional[Any]: a_ : str = """mock_framework""" # Framework provided - return whatever the user provides a_ : Optional[int] = FeaturesManager.determine_framework(self.test_model , _lowercase ) self.assertEqual(_lowercase , _lowercase ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(_lowercase ) a_ : Optional[int] = FeaturesManager.determine_framework(_lowercase , _lowercase ) self.assertEqual(_lowercase , _lowercase ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(_lowercase ) a_ : List[str] = FeaturesManager.determine_framework(_lowercase , _lowercase ) self.assertEqual(_lowercase , _lowercase ) def UpperCamelCase__ ( self ) -> Union[str, Any]: # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(_lowercase ) a_ : Union[str, Any] = FeaturesManager.determine_framework(_lowercase ) self.assertEqual(_lowercase , self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(_lowercase ) a_ : Union[str, Any] = FeaturesManager.determine_framework(_lowercase ) self.assertEqual(_lowercase , self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(_lowercase ): a_ : Union[str, Any] = FeaturesManager.determine_framework(_lowercase ) def UpperCamelCase__ ( self ) -> List[Any]: a_ : int = MagicMock(return_value=_lowercase ) with patch("""transformers.onnx.features.is_tf_available""" , _lowercase ): a_ : Union[str, Any] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_lowercase , self.framework_pt ) # PyTorch not in environment -> use TensorFlow a_ : Dict = MagicMock(return_value=_lowercase ) with patch("""transformers.onnx.features.is_torch_available""" , _lowercase ): a_ : Union[str, Any] = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_lowercase , self.framework_tf ) # Both in environment -> use PyTorch a_ : Optional[Any] = MagicMock(return_value=_lowercase ) a_ : List[Any] = MagicMock(return_value=_lowercase ) with patch("""transformers.onnx.features.is_tf_available""" , _lowercase ), patch( """transformers.onnx.features.is_torch_available""" , _lowercase ): a_ : Any = FeaturesManager.determine_framework(self.test_model ) self.assertEqual(_lowercase , self.framework_pt ) # Both not in environment -> raise error a_ : List[str] = MagicMock(return_value=_lowercase ) a_ : Optional[Any] = MagicMock(return_value=_lowercase ) with patch("""transformers.onnx.features.is_tf_available""" , _lowercase ), patch( """transformers.onnx.features.is_torch_available""" , _lowercase ): with self.assertRaises(_lowercase ): a_ : Dict = FeaturesManager.determine_framework(self.test_model )
540
0
import argparse import json import os import re import torch from transformers import BloomConfig, BloomModel from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME from transformers.utils import logging logging.set_verbosity_info() _UpperCAmelCase = [ "word_embeddings_layernorm.weight", "word_embeddings_layernorm.bias", "input_layernorm.weight", "input_layernorm.bias", "post_attention_layernorm.weight", "post_attention_layernorm.bias", "self_attention.dense.bias", "mlp.dense_4h_to_h.bias", "ln_f.weight", "ln_f.bias", ] _UpperCAmelCase = [ "mlp.dense_4h_to_h.weight", "self_attention.dense.weight", ] def _lowerCamelCase ( _a , _a ): """simple docstring""" _lowerCamelCase = { '''word_embeddings.weight''': '''word_embeddings.weight''', '''word_embeddings.norm.weight''': '''word_embeddings_layernorm.weight''', '''word_embeddings.norm.bias''': '''word_embeddings_layernorm.bias''', '''weight''': '''ln_f.weight''', '''bias''': '''ln_f.bias''', } if key in layer_rename_map: return layer_rename_map[key] # Handle transformer blocks _lowerCamelCase = int(re.match(R'''.*layer_(\d*).*''' , _a )[1] ) layer_number -= 3 return F'''h.{layer_number}.''' + key def _lowerCamelCase ( _a ): """simple docstring""" if dtype == torch.bool: return 1 / 8 _lowerCamelCase = re.search(R'''[^\d](\d+)$''' , str(_a ) ) if bit_search is None: raise ValueError(F'''`dtype` is not a valid dtype: {dtype}.''' ) _lowerCamelCase = int(bit_search.groups()[0] ) return bit_size // 8 def _lowerCamelCase ( _a , _a , _a , _a , _a ): """simple docstring""" if bloom_config_file == "": _lowerCamelCase = BloomConfig() else: _lowerCamelCase = BloomConfig.from_json_file(_a ) if shard_model: _lowerCamelCase = os.listdir(_a ) _lowerCamelCase = sorted(filter(lambda _a : s.startswith('''layer''' ) and "model_00" in s , _a ) ) _lowerCamelCase = {'''weight_map''': {}, '''metadata''': {}} _lowerCamelCase = 0 _lowerCamelCase = None _lowerCamelCase = BloomConfig() for j, file in enumerate(_a ): print('''Processing file: {}'''.format(_a ) ) _lowerCamelCase = None for i in range(_a ): # load all TP files _lowerCamelCase = file.replace('''model_00''' , F'''model_0{i}''' ) _lowerCamelCase = torch.load(os.path.join(_a , _a ) , map_location='''cpu''' ) # Rename keys in the transformers names _lowerCamelCase = list(temp.keys() ) for key in keys: _lowerCamelCase = temp.pop(_a ) if tensors is None: _lowerCamelCase = temp else: for key in tensors.keys(): if any(key.endswith(_a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel _lowerCamelCase = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks _lowerCamelCase = torch.cat([tensors[key], temp[key]] , dim=_a ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(_a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): _lowerCamelCase = tensors[key] / pretraining_tp torch.save( _a , os.path.join( _a , '''pytorch_model_{}-of-{}.bin'''.format(str(j + 1 ).zfill(5 ) , str(len(_a ) ).zfill(5 ) ) , ) , ) for key in tensors.keys(): _lowerCamelCase = tensors[key] total_size += value.numel() * get_dtype_size(value.dtype ) if key not in index_dict["weight_map"]: _lowerCamelCase = '''pytorch_model_{}-of-{}.bin'''.format( str(j + 1 ).zfill(5 ) , str(len(_a ) ).zfill(5 ) ) _lowerCamelCase = BloomConfig() _lowerCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME _lowerCamelCase = total_size with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) with open(os.path.join(_a , WEIGHTS_NAME + '''.index.json''' ) , '''w''' , encoding='''utf-8''' ) as f: _lowerCamelCase = json.dumps(_a , indent=2 , sort_keys=_a ) + '''\n''' f.write(_a ) else: _lowerCamelCase = BloomModel(_a ) _lowerCamelCase = os.listdir(_a ) _lowerCamelCase = sorted(filter(lambda _a : s.startswith('''layer''' ) and "model_00" in s , _a ) ) _lowerCamelCase = None for i, file in enumerate(_a ): _lowerCamelCase = None for i in range(_a ): # load all TP files _lowerCamelCase = file.replace('''model_00''' , F'''model_0{i}''' ) _lowerCamelCase = torch.load(os.path.join(_a , _a ) , map_location='''cpu''' ) # Rename keys in the transformers names _lowerCamelCase = list(temp.keys() ) for key in keys: _lowerCamelCase = temp.pop(_a ) if tensors is None: _lowerCamelCase = temp else: for key in tensors.keys(): # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425) if any(key.endswith(_a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): tensors[key] += temp[key] else: # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel _lowerCamelCase = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0 # We concatenate these weights accross TP ranks _lowerCamelCase = torch.cat([tensors[key], temp[key]] , dim=_a ) # Divide by the number of TP the weights we want to average for key in tensors.keys(): if any(key.endswith(_a ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ): _lowerCamelCase = tensors[key] / pretraining_tp _lowerCamelCase = model.load_state_dict(_a , strict=_a ) assert not other_keys.unexpected_keys, F'''The keys {other_keys.unexpected_keys} are unexpected''' if missing_keys is None: _lowerCamelCase = set(other_keys.missing_keys ) else: _lowerCamelCase = missing_keys.intersection(set(other_keys.missing_keys ) ) assert not missing_keys, F'''The keys {missing_keys} are missing''' # Save pytorch-model os.makedirs(_a , exist_ok=_a ) _lowerCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME _lowerCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'''Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}''' ) if config.torch_dtype is not None: _lowerCamelCase = model.to(config.torch_dtype ) torch.save(model.state_dict() , _a ) print(F'''Save configuration file to {pytorch_config_dump_path}''' ) with open(_a , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( "--bloom_checkpoint_path", default=None, type=str, required=True, help="Path to the Megatron-LM checkpoint path.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--bloom_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--shard_model", action="store_true", help="An optional setting to shard the output model \nThis enables sharding the converted checkpoint", ) parser.add_argument( "--pretraining_tp", default=4, type=int, help="Pretraining TP rank that has been used when training the model in Megatron-LM \n", ) _UpperCAmelCase = parser.parse_args() convert_bloom_checkpoint_to_pytorch( args.bloom_checkpoint_path, args.bloom_config_file, args.pytorch_dump_folder_path, args.shard_model, args.pretraining_tp, )
297
import heapq def _lowerCamelCase ( _a ): """simple docstring""" _lowerCamelCase = [] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(_a , [-1 * len(_a ), (key, value)] ) # chosen_vertices = set of chosen vertices _lowerCamelCase = set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices _lowerCamelCase = heapq.heappop(_a )[1][0] chosen_vertices.add(_a ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: _lowerCamelCase = elem[1][1].index(_a ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(_a ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _UpperCAmelCase = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(F'Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}')
297
1
"""simple docstring""" import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html _UpperCAmelCase = """platform""" import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def __magic_name__ ( lowercase , lowercase , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , lowercase=None , ): if attention_mask is None: SCREAMING_SNAKE_CASE_: int =np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE_: Optional[int] =np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: SCREAMING_SNAKE_CASE_: Dict =np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE_: int =np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE_: Any =np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class a : def __init__( self : List[Any] , lowerCAmelCase : Optional[int] , lowerCAmelCase : Optional[int]=13 , lowerCAmelCase : Dict=7 , lowerCAmelCase : Union[str, Any]=True , lowerCAmelCase : Optional[Any]=False , lowerCAmelCase : str=99 , lowerCAmelCase : int=16 , lowerCAmelCase : Any=2 , lowerCAmelCase : List[str]=4 , lowerCAmelCase : int=4 , lowerCAmelCase : Any="gelu" , lowerCAmelCase : str=0.1 , lowerCAmelCase : Optional[int]=0.1 , lowerCAmelCase : Optional[int]=32 , lowerCAmelCase : int=2 , lowerCAmelCase : Tuple=1 , lowerCAmelCase : Optional[int]=0 , lowerCAmelCase : str=0.0_2 , ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_: str =parent SCREAMING_SNAKE_CASE_: List[Any] =batch_size SCREAMING_SNAKE_CASE_: Any =seq_length SCREAMING_SNAKE_CASE_: str =is_training SCREAMING_SNAKE_CASE_: Dict =use_labels SCREAMING_SNAKE_CASE_: Optional[Any] =vocab_size SCREAMING_SNAKE_CASE_: List[str] =hidden_size SCREAMING_SNAKE_CASE_: Dict =num_hidden_layers SCREAMING_SNAKE_CASE_: Any =num_attention_heads SCREAMING_SNAKE_CASE_: Dict =intermediate_size SCREAMING_SNAKE_CASE_: List[Any] =hidden_act SCREAMING_SNAKE_CASE_: List[str] =hidden_dropout_prob SCREAMING_SNAKE_CASE_: Any =attention_probs_dropout_prob SCREAMING_SNAKE_CASE_: List[str] =max_position_embeddings SCREAMING_SNAKE_CASE_: Union[str, Any] =eos_token_id SCREAMING_SNAKE_CASE_: List[str] =pad_token_id SCREAMING_SNAKE_CASE_: Optional[Any] =bos_token_id SCREAMING_SNAKE_CASE_: Tuple =initializer_range def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: int =np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) SCREAMING_SNAKE_CASE_: Any =np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) SCREAMING_SNAKE_CASE_: List[str] =shift_tokens_right(lowerCAmelCase , 1 , 2 ) SCREAMING_SNAKE_CASE_: Union[str, Any] =BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: List[str] =prepare_blenderbot_inputs_dict(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) return config, inputs_dict def lowerCamelCase__ ( self : int ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] =self.prepare_config_and_inputs() return config, inputs_dict def lowerCamelCase__ ( self : Optional[int] , lowerCAmelCase : Dict , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Tuple ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =20 SCREAMING_SNAKE_CASE_: int =model_class_name(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =model.encode(inputs_dict["""input_ids"""] ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Any =( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) SCREAMING_SNAKE_CASE_: Dict =model.init_cache(decoder_input_ids.shape[0] , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) SCREAMING_SNAKE_CASE_: Union[str, Any] =jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) SCREAMING_SNAKE_CASE_: Optional[int] =model.decode( decoder_input_ids[:, :-1] , lowerCAmelCase , decoder_attention_mask=lowerCAmelCase , past_key_values=lowerCAmelCase , decoder_position_ids=lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Union[str, Any] =jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =model.decode( decoder_input_ids[:, -1:] , lowerCAmelCase , decoder_attention_mask=lowerCAmelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Any =model.decode(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) def lowerCamelCase__ ( self : str , lowerCAmelCase : Optional[int] , lowerCAmelCase : int , lowerCAmelCase : Tuple ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE_: Union[str, Any] =20 SCREAMING_SNAKE_CASE_: Union[str, Any] =model_class_name(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: str =model.encode(inputs_dict["""input_ids"""] ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) SCREAMING_SNAKE_CASE_: int =jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) SCREAMING_SNAKE_CASE_: Optional[Any] =model.init_cache(decoder_input_ids.shape[0] , lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) SCREAMING_SNAKE_CASE_: Dict =model.decode( decoder_input_ids[:, :-1] , lowerCAmelCase , decoder_attention_mask=lowerCAmelCase , past_key_values=lowerCAmelCase , decoder_position_ids=lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: List[Any] =jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =model.decode( decoder_input_ids[:, -1:] , lowerCAmelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowerCAmelCase , decoder_position_ids=lowerCAmelCase , ) SCREAMING_SNAKE_CASE_: Union[str, Any] =model.decode(lowerCAmelCase , lowerCAmelCase , decoder_attention_mask=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}''' ) @require_flax class a ( unittest.TestCase ): UpperCamelCase : Any = 9_9 def lowerCamelCase__ ( self : Tuple ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[str] =np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) SCREAMING_SNAKE_CASE_: Dict =input_ids.shape[0] SCREAMING_SNAKE_CASE_: int =BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def lowerCamelCase__ ( self : List[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Dict =self._get_config_and_data() SCREAMING_SNAKE_CASE_: Union[str, Any] =FlaxBlenderbotSmallForConditionalGeneration(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[Any] =lm_model(input_ids=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: int =(batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["""logits"""].shape , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[int] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Any =BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) SCREAMING_SNAKE_CASE_: Optional[int] =FlaxBlenderbotSmallForConditionalGeneration(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: List[str] =np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE_: List[Any] =np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE_: Optional[int] =lm_model(input_ids=lowerCAmelCase , decoder_input_ids=lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[Any] =(*summary.shape, config.vocab_size) self.assertEqual(outputs["""logits"""].shape , lowerCAmelCase ) def lowerCamelCase__ ( self : Any ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE_: List[Any] =np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE_: List[str] =shift_tokens_right(lowerCAmelCase , 1 , 2 ) SCREAMING_SNAKE_CASE_: int =np.equal(lowerCAmelCase , 1 ).astype(np.floataa ).sum() SCREAMING_SNAKE_CASE_: Union[str, Any] =np.equal(lowerCAmelCase , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(lowerCAmelCase , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class a ( UpperCAmelCase__ , unittest.TestCase , UpperCAmelCase__ ): UpperCamelCase : Tuple = True UpperCamelCase : int = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) UpperCamelCase : Union[str, Any] = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def lowerCamelCase__ ( self : Optional[Any] ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =FlaxBlenderbotSmallModelTester(self ) def lowerCamelCase__ ( self : Dict ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Optional[int] =self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Optional[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[str] =self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Optional[Any]: '''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: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE_: Optional[Any] =self._prepare_for_class(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =model_class(lowerCAmelCase ) @jax.jit def encode_jitted(lowerCAmelCase : Any , lowerCAmelCase : Any=None , **lowerCAmelCase : Dict ): return model.encode(input_ids=lowerCAmelCase , attention_mask=lowerCAmelCase ) with self.subTest("""JIT Enabled""" ): SCREAMING_SNAKE_CASE_: Tuple =encode_jitted(**lowerCAmelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): SCREAMING_SNAKE_CASE_: Union[str, Any] =encode_jitted(**lowerCAmelCase ).to_tuple() self.assertEqual(len(lowerCAmelCase ) , len(lowerCAmelCase ) ) for jitted_output, output in zip(lowerCAmelCase , lowerCAmelCase ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( self : Dict ) -> Dict: '''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: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE_: str =model_class(lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) SCREAMING_SNAKE_CASE_: List[str] ={ """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(lowerCAmelCase : Dict , lowerCAmelCase : str , lowerCAmelCase : Optional[Any] ): return model.decode( decoder_input_ids=lowerCAmelCase , decoder_attention_mask=lowerCAmelCase , encoder_outputs=lowerCAmelCase , ) with self.subTest("""JIT Enabled""" ): SCREAMING_SNAKE_CASE_: List[str] =decode_jitted(**lowerCAmelCase ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): SCREAMING_SNAKE_CASE_: str =decode_jitted(**lowerCAmelCase ).to_tuple() self.assertEqual(len(lowerCAmelCase ) , len(lowerCAmelCase ) ) for jitted_output, output in zip(lowerCAmelCase , lowerCAmelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowerCamelCase__ ( self : str ) -> List[str]: '''simple docstring''' for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE_: List[str] =model_class_name.from_pretrained("""facebook/blenderbot_small-90M""" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids SCREAMING_SNAKE_CASE_: Union[str, Any] =np.ones((1, 1) ) * model.config.eos_token_id SCREAMING_SNAKE_CASE_: List[Any] =model(lowerCAmelCase ) self.assertIsNotNone(lowerCAmelCase )
409
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class a ( UpperCAmelCase__ ): UpperCamelCase : Any = 'Speech2TextFeatureExtractor' UpperCamelCase : Optional[Any] = 'Speech2TextTokenizer' def __init__( self : Optional[Any] , lowerCAmelCase : List[str] , lowerCAmelCase : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' super().__init__(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =self.feature_extractor SCREAMING_SNAKE_CASE_: List[Any] =False def __call__( self : Dict , *lowerCAmelCase : str , **lowerCAmelCase : str ) -> str: '''simple docstring''' if self._in_target_context_manager: return self.current_processor(*lowerCAmelCase , **lowerCAmelCase ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) SCREAMING_SNAKE_CASE_: Tuple =kwargs.pop("""raw_speech""" ) else: SCREAMING_SNAKE_CASE_: int =kwargs.pop("""audio""" , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] =kwargs.pop("""sampling_rate""" , lowerCAmelCase ) SCREAMING_SNAKE_CASE_: Tuple =kwargs.pop("""text""" , lowerCAmelCase ) if len(lowerCAmelCase ) > 0: SCREAMING_SNAKE_CASE_: List[str] =args[0] SCREAMING_SNAKE_CASE_: List[str] =args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: SCREAMING_SNAKE_CASE_: Optional[int] =self.feature_extractor(lowerCAmelCase , *lowerCAmelCase , sampling_rate=lowerCAmelCase , **lowerCAmelCase ) if text is not None: SCREAMING_SNAKE_CASE_: Union[str, Any] =self.tokenizer(lowerCAmelCase , **lowerCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE_: Any =encodings["""input_ids"""] return inputs def lowerCamelCase__ ( self : Any , *lowerCAmelCase : Any , **lowerCAmelCase : Tuple ) -> Any: '''simple docstring''' return self.tokenizer.batch_decode(*lowerCAmelCase , **lowerCAmelCase ) def lowerCamelCase__ ( self : Tuple , *lowerCAmelCase : Any , **lowerCAmelCase : int ) -> Any: '''simple docstring''' return self.tokenizer.decode(*lowerCAmelCase , **lowerCAmelCase ) @contextmanager def lowerCamelCase__ ( self : Tuple ) -> Tuple: '''simple docstring''' warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) SCREAMING_SNAKE_CASE_: Optional[Any] =True SCREAMING_SNAKE_CASE_: Dict =self.tokenizer yield SCREAMING_SNAKE_CASE_: int =self.feature_extractor SCREAMING_SNAKE_CASE_: str =False
409
1
import unittest from transformers import AlbertTokenizer, AlbertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase :Dict = get_tests_dir('''fixtures/spiece.model''') @require_sentencepiece @require_tokenizers class _lowerCAmelCase ( __UpperCAmelCase , unittest.TestCase ): __SCREAMING_SNAKE_CASE : Any = AlbertTokenizer __SCREAMING_SNAKE_CASE : Tuple = AlbertTokenizerFast __SCREAMING_SNAKE_CASE : int = True __SCREAMING_SNAKE_CASE : str = True __SCREAMING_SNAKE_CASE : Union[str, Any] = True def _a (self ): super().setUp() # We have a SentencePiece fixture for testing A_ : Optional[int] = AlbertTokenizer(lowercase ) tokenizer.save_pretrained(self.tmpdirname ) def _a (self , lowercase ): A_ : Dict = """this is a test""" A_ : Optional[int] = """this is a test""" return input_text, output_text def _a (self ): A_ : Optional[int] = """<pad>""" A_ : int = 0 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 ): A_ : Optional[Any] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<pad>""" ) self.assertEqual(vocab_keys[1] , """<unk>""" ) self.assertEqual(vocab_keys[-1] , """▁eloquent""" ) self.assertEqual(len(lowercase ) , 30000 ) def _a (self ): self.assertEqual(self.get_tokenizer().vocab_size , 30000 ) def _a (self ): if not self.test_rust_tokenizer: return A_ : Tuple = self.get_tokenizer() A_ : Optional[int] = self.get_rust_tokenizer() A_ : Tuple = """I was born in 92000, and this is falsé.""" A_ : Tuple = tokenizer.tokenize(lowercase ) A_ : str = rust_tokenizer.tokenize(lowercase ) self.assertListEqual(lowercase , lowercase ) A_ : Tuple = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A_ : Optional[Any] = rust_tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) A_ : Optional[Any] = self.get_rust_tokenizer() A_ : Optional[int] = tokenizer.encode(lowercase ) A_ : List[Any] = rust_tokenizer.encode(lowercase ) self.assertListEqual(lowercase , lowercase ) def _a (self ): A_ : Tuple = AlbertTokenizer(lowercase , keep_accents=lowercase ) A_ : int = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(lowercase , ["""▁this""", """▁is""", """▁a""", """▁test"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase ) , [48, 25, 21, 1289] ) A_ : List[str] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( lowercase , ["""▁i""", """▁was""", """▁born""", """▁in""", """▁9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """é""", """."""] ) A_ : Any = tokenizer.convert_tokens_to_ids(lowercase ) self.assertListEqual(lowercase , [31, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] ) A_ : Optional[Any] = tokenizer.convert_ids_to_tokens(lowercase ) self.assertListEqual( lowercase , ["""▁i""", """▁was""", """▁born""", """▁in""", """▁9""", """2000""", """,""", """▁and""", """▁this""", """▁is""", """▁fal""", """s""", """<unk>""", """."""] , ) def _a (self ): A_ : int = AlbertTokenizer(lowercase ) A_ : Optional[int] = tokenizer.encode("""sequence builders""" ) A_ : Optional[int] = tokenizer.encode("""multi-sequence build""" ) A_ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(lowercase ) A_ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(lowercase , lowercase ) assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [ tokenizer.sep_token_id ] @slow def _a (self ): A_ : int = {"""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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """input_ids""": [[2, 21970, 13, 5, 6092, 167, 28, 7103, 2153, 673, 8, 7028, 12051, 18, 17, 7103, 2153, 673, 8, 3515, 18684, 8, 4461, 6, 1927, 297, 8, 12060, 2607, 18, 13, 5, 4461, 15, 10538, 38, 8, 135, 15, 822, 58, 15, 993, 10363, 15, 1460, 8005, 4461, 15, 993, 255, 2328, 9, 9, 9, 6, 26, 1112, 816, 3260, 13, 5, 103, 2377, 6, 17, 1112, 816, 2782, 13, 5, 103, 10641, 6, 29, 84, 2512, 2430, 782, 18684, 2761, 19, 808, 2430, 2556, 17, 855, 1480, 9477, 4091, 128, 11712, 15, 7103, 2153, 673, 17, 24883, 9990, 9, 3], [2, 11502, 25, 1006, 20, 782, 8, 11809, 855, 1732, 19393, 18667, 37, 367, 21018, 69, 1854, 34, 11860, 19124, 27, 156, 225, 17, 193, 4141, 19, 65, 9124, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 14, 2231, 886, 2385, 17659, 84, 14, 16792, 1952, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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=lowercase , model_name="""albert-base-v2""" , revision="""6b6560eaf5ff2e250b00c50f380c5389a9c2d82e""" , )
716
'''simple docstring''' import pytest import requests from datasets.utils.file_utils import http_head from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline @pytest.mark.integration def a ( ): '''simple docstring''' with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ): with pytest.raises(lowerCamelCase__ ): requests.request("""GET""" , """https://huggingface.co""" ) with pytest.raises(requests.exceptions.ConnectTimeout ): requests.request("""GET""" , """https://huggingface.co""" , timeout=1.0 ) @pytest.mark.integration def a ( ): '''simple docstring''' with offline(OfflineSimulationMode.CONNECTION_FAILS ): with pytest.raises(requests.exceptions.ConnectionError ): requests.request("""GET""" , """https://huggingface.co""" ) def a ( ): '''simple docstring''' with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ): with pytest.raises(lowerCamelCase__ ): http_head("""https://huggingface.co""" )
686
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase_ : Union[str, Any] = { '''configuration_tapas''': ['''TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TapasConfig'''], '''tokenization_tapas''': ['''TapasTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ : Optional[int] = [ '''TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TapasForMaskedLM''', '''TapasForQuestionAnswering''', '''TapasForSequenceClassification''', '''TapasModel''', '''TapasPreTrainedModel''', '''load_tf_weights_in_tapas''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ : Dict = [ '''TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFTapasForMaskedLM''', '''TFTapasForQuestionAnswering''', '''TFTapasForSequenceClassification''', '''TFTapasModel''', '''TFTapasPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys lowercase_ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
572
"""simple docstring""" def _lowerCAmelCase ( ) -> int: return [ a * b * (1_0_0_0 - a - b) for a in range(1, 9_9_9 ) for b in range(lowerCamelCase__, 9_9_9 ) if (a * a + b * b == (1_0_0_0 - a - b) ** 2) ][0] if __name__ == "__main__": print(F'{solution() = }')
572
1
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): lowerCamelCase__ = { '''linear''': PIL.Image.Resampling.BILINEAR, '''bilinear''': PIL.Image.Resampling.BILINEAR, '''bicubic''': PIL.Image.Resampling.BICUBIC, '''lanczos''': PIL.Image.Resampling.LANCZOS, '''nearest''': PIL.Image.Resampling.NEAREST, } else: lowerCamelCase__ = { '''linear''': PIL.Image.LINEAR, '''bilinear''': PIL.Image.BILINEAR, '''bicubic''': PIL.Image.BICUBIC, '''lanczos''': PIL.Image.LANCZOS, '''nearest''': PIL.Image.NEAREST, } def lowercase_ ( SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" snake_case__ : List[str] =(images / 2 + 0.5).clamp(0 , 1 ) snake_case__ : str =images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() snake_case__ : Optional[int] =numpy_to_pil(snake_case__ ) return images def lowercase_ ( SCREAMING_SNAKE_CASE : Any ): """simple docstring""" if images.ndim == 3: snake_case__ : Any =images[None, ...] snake_case__ : List[str] =(images * 2_55).round().astype('''uint8''' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images snake_case__ : Optional[int] =[Image.fromarray(image.squeeze() , mode='''L''' ) for image in images] else: snake_case__ : List[Any] =[Image.fromarray(snake_case__ ) for image in images] return pil_images
700
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class _lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" lowerCAmelCase__ =42 lowerCAmelCase__ =jnp.floataa lowerCAmelCase__ =True def UpperCAmelCase ( self ) -> Union[str, Any]: """simple docstring""" super().setup() snake_case__ : int =nn.Dense(5 , dtype=self.dtype ) def __call__( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" snake_case__ : int =super().__call__(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) snake_case__ : Union[str, Any] =self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class _lowerCAmelCase ( __UpperCamelCase ): """simple docstring""" lowerCAmelCase__ =FlaxBigBirdForNaturalQuestionsModule def lowercase_ ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Tuple ): """simple docstring""" def cross_entropy(SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Optional[Any]=None ): snake_case__ : Optional[Any] =logits.shape[-1] snake_case__ : List[str] =(labels[..., None] == jnp.arange(SCREAMING_SNAKE_CASE )[None]).astype('''f4''' ) snake_case__ : str =jax.nn.log_softmax(SCREAMING_SNAKE_CASE , axis=-1 ) snake_case__ : Any =-jnp.sum(labels * logits , axis=-1 ) if reduction is not None: snake_case__ : Tuple =reduction(SCREAMING_SNAKE_CASE ) return loss snake_case__ : List[Any] =partial(SCREAMING_SNAKE_CASE , reduction=jnp.mean ) snake_case__ : Optional[int] =cross_entropy(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) snake_case__ : Any =cross_entropy(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) snake_case__ : int =cross_entropy(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class _lowerCAmelCase : """simple docstring""" lowerCAmelCase__ ="google/bigbird-roberta-base" lowerCAmelCase__ =3_000 lowerCAmelCase__ =10_500 lowerCAmelCase__ =128 lowerCAmelCase__ =3 lowerCAmelCase__ =1 lowerCAmelCase__ =5 # tx_args lowerCAmelCase__ =3e-5 lowerCAmelCase__ =0.0 lowerCAmelCase__ =20_000 lowerCAmelCase__ =0.0_0_9_5 lowerCAmelCase__ ="bigbird-roberta-natural-questions" lowerCAmelCase__ ="training-expt" lowerCAmelCase__ ="data/nq-training.jsonl" lowerCAmelCase__ ="data/nq-validation.jsonl" def UpperCAmelCase ( self ) -> Any: """simple docstring""" os.makedirs(self.base_dir , exist_ok=__SCREAMING_SNAKE_CASE ) snake_case__ : int =os.path.join(self.base_dir , self.save_dir ) snake_case__ : Union[str, Any] =self.batch_size_per_device * jax.device_count() @dataclass class _lowerCAmelCase : """simple docstring""" lowerCAmelCase__ =42 lowerCAmelCase__ =4_096 # no dynamic padding on TPUs def __call__( self , __SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" snake_case__ : Dict =self.collate_fn(__SCREAMING_SNAKE_CASE ) snake_case__ : str =jax.tree_util.tree_map(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return batch def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" snake_case__, snake_case__ : Tuple =self.fetch_inputs(features['''input_ids'''] ) snake_case__ : str ={ '''input_ids''': jnp.array(__SCREAMING_SNAKE_CASE , dtype=jnp.intaa ), '''attention_mask''': jnp.array(__SCREAMING_SNAKE_CASE , dtype=jnp.intaa ), '''start_labels''': jnp.array(features['''start_token'''] , dtype=jnp.intaa ), '''end_labels''': jnp.array(features['''end_token'''] , dtype=jnp.intaa ), '''pooled_labels''': jnp.array(features['''category'''] , dtype=jnp.intaa ), } return batch def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" snake_case__ : List[Any] =[self._fetch_inputs(__SCREAMING_SNAKE_CASE ) for ids in input_ids] return zip(*__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" snake_case__ : Optional[Any] =[1 for _ in range(len(__SCREAMING_SNAKE_CASE ) )] while len(__SCREAMING_SNAKE_CASE ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def lowercase_ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : List[Any] , SCREAMING_SNAKE_CASE : Optional[int]=None ): """simple docstring""" if seed is not None: snake_case__ : Union[str, Any] =dataset.shuffle(seed=SCREAMING_SNAKE_CASE ) for i in range(len(SCREAMING_SNAKE_CASE ) // batch_size ): snake_case__ : Any =dataset[i * batch_size : (i + 1) * batch_size] yield dict(SCREAMING_SNAKE_CASE ) @partial(jax.pmap , axis_name='''batch''' ) def lowercase_ ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : Union[str, Any] , **SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" def loss_fn(SCREAMING_SNAKE_CASE : int ): snake_case__ : Any =model_inputs.pop('''start_labels''' ) snake_case__ : List[Any] =model_inputs.pop('''end_labels''' ) snake_case__ : List[Any] =model_inputs.pop('''pooled_labels''' ) snake_case__ : str =state.apply_fn(**SCREAMING_SNAKE_CASE , params=SCREAMING_SNAKE_CASE , dropout_rng=SCREAMING_SNAKE_CASE , train=SCREAMING_SNAKE_CASE ) snake_case__, snake_case__, snake_case__ : int =outputs return state.loss_fn( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , ) snake_case__, snake_case__ : Optional[Any] =jax.random.split(SCREAMING_SNAKE_CASE ) snake_case__ : int =jax.value_and_grad(SCREAMING_SNAKE_CASE ) snake_case__, snake_case__ : int =grad_fn(state.params ) snake_case__ : List[str] =jax.lax.pmean({'''loss''': loss} , axis_name='''batch''' ) snake_case__ : List[str] =jax.lax.pmean(SCREAMING_SNAKE_CASE , '''batch''' ) snake_case__ : Optional[Any] =state.apply_gradients(grads=SCREAMING_SNAKE_CASE ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name='''batch''' ) def lowercase_ ( SCREAMING_SNAKE_CASE : Optional[Any] , **SCREAMING_SNAKE_CASE : List[str] ): """simple docstring""" snake_case__ : int =model_inputs.pop('''start_labels''' ) snake_case__ : Tuple =model_inputs.pop('''end_labels''' ) snake_case__ : Optional[int] =model_inputs.pop('''pooled_labels''' ) snake_case__ : Any =state.apply_fn(**SCREAMING_SNAKE_CASE , params=state.params , train=SCREAMING_SNAKE_CASE ) snake_case__, snake_case__, snake_case__ : Optional[Any] =outputs snake_case__ : Optional[int] =state.loss_fn(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) snake_case__ : int =jax.lax.pmean({'''loss''': loss} , axis_name='''batch''' ) return metrics class _lowerCAmelCase ( train_state.TrainState ): """simple docstring""" lowerCAmelCase__ =struct.field(pytree_node=__UpperCamelCase ) @dataclass class _lowerCAmelCase : """simple docstring""" lowerCAmelCase__ =42 lowerCAmelCase__ =42 lowerCAmelCase__ =42 lowerCAmelCase__ =42 lowerCAmelCase__ =42 lowerCAmelCase__ =42 lowerCAmelCase__ =None def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=None ) -> Tuple: """simple docstring""" snake_case__ : List[Any] =model.params snake_case__ : str =TrainState.create( apply_fn=model.__call__ , params=__SCREAMING_SNAKE_CASE , tx=__SCREAMING_SNAKE_CASE , loss_fn=__SCREAMING_SNAKE_CASE , ) if ckpt_dir is not None: snake_case__, snake_case__, snake_case__, snake_case__, snake_case__ : int =restore_checkpoint(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Any ={ '''lr''': args.lr, '''init_lr''': args.init_lr, '''warmup_steps''': args.warmup_steps, '''num_train_steps''': num_train_steps, '''weight_decay''': args.weight_decay, } snake_case__, snake_case__ : Union[str, Any] =build_tx(**__SCREAMING_SNAKE_CASE ) snake_case__ : str =train_state.TrainState( step=__SCREAMING_SNAKE_CASE , apply_fn=model.__call__ , params=__SCREAMING_SNAKE_CASE , tx=__SCREAMING_SNAKE_CASE , opt_state=__SCREAMING_SNAKE_CASE , ) snake_case__ : Optional[int] =args snake_case__ : Union[str, Any] =data_collator snake_case__ : Any =lr snake_case__ : Tuple =params snake_case__ : Tuple =jax_utils.replicate(__SCREAMING_SNAKE_CASE ) return state def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" snake_case__ : Union[str, Any] =self.args snake_case__ : List[str] =len(__SCREAMING_SNAKE_CASE ) // args.batch_size snake_case__ : str =jax.random.PRNGKey(0 ) snake_case__ : List[Any] =jax.random.split(__SCREAMING_SNAKE_CASE , jax.device_count() ) for epoch in range(args.max_epochs ): snake_case__ : Optional[Any] =jnp.array(0 , dtype=jnp.floataa ) snake_case__ : int =get_batched_dataset(__SCREAMING_SNAKE_CASE , args.batch_size , seed=__SCREAMING_SNAKE_CASE ) snake_case__ : Any =0 for batch in tqdm(__SCREAMING_SNAKE_CASE , total=__SCREAMING_SNAKE_CASE , desc=f'''Running EPOCH-{epoch}''' ): snake_case__ : Tuple =self.data_collator(__SCREAMING_SNAKE_CASE ) snake_case__, snake_case__, snake_case__ : int =self.train_step_fn(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) running_loss += jax_utils.unreplicate(metrics['''loss'''] ) i += 1 if i % args.logging_steps == 0: snake_case__ : List[str] =jax_utils.unreplicate(state.step ) snake_case__ : Optional[int] =running_loss.item() / i snake_case__ : Dict =self.scheduler_fn(state_step - 1 ) snake_case__ : Optional[int] =self.evaluate(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] ={ '''step''': state_step.item(), '''eval_loss''': eval_loss.item(), '''tr_loss''': tr_loss, '''lr''': lr.item(), } tqdm.write(str(__SCREAMING_SNAKE_CASE ) ) self.logger.log(__SCREAMING_SNAKE_CASE , commit=__SCREAMING_SNAKE_CASE ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f'''-e{epoch}-s{i}''' , state=__SCREAMING_SNAKE_CASE ) def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" snake_case__ : int =get_batched_dataset(__SCREAMING_SNAKE_CASE , self.args.batch_size ) snake_case__ : Any =len(__SCREAMING_SNAKE_CASE ) // self.args.batch_size snake_case__ : List[Any] =jnp.array(0 , dtype=jnp.floataa ) snake_case__ : Optional[Any] =0 for batch in tqdm(__SCREAMING_SNAKE_CASE , total=__SCREAMING_SNAKE_CASE , desc='''Evaluating ... ''' ): snake_case__ : Optional[int] =self.data_collator(__SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] =self.val_step_fn(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) running_loss += jax_utils.unreplicate(metrics['''loss'''] ) i += 1 return running_loss / i def UpperCAmelCase ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" snake_case__ : Tuple =jax_utils.unreplicate(__SCREAMING_SNAKE_CASE ) print(f'''SAVING CHECKPOINT IN {save_dir}''' , end=''' ... ''' ) self.model_save_fn(__SCREAMING_SNAKE_CASE , params=state.params ) with open(os.path.join(__SCREAMING_SNAKE_CASE , '''opt_state.msgpack''' ) , '''wb''' ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args , os.path.join(__SCREAMING_SNAKE_CASE , '''args.joblib''' ) ) joblib.dump(self.data_collator , os.path.join(__SCREAMING_SNAKE_CASE , '''data_collator.joblib''' ) ) with open(os.path.join(__SCREAMING_SNAKE_CASE , '''training_state.json''' ) , '''w''' ) as f: json.dump({'''step''': state.step.item()} , __SCREAMING_SNAKE_CASE ) print('''DONE''' ) def lowercase_ ( SCREAMING_SNAKE_CASE : Dict , SCREAMING_SNAKE_CASE : int ): """simple docstring""" print(F'''RESTORING CHECKPOINT FROM {save_dir}''' , end=''' ... ''' ) with open(os.path.join(SCREAMING_SNAKE_CASE , '''flax_model.msgpack''' ) , '''rb''' ) as f: snake_case__ : Optional[Any] =from_bytes(state.params , f.read() ) with open(os.path.join(SCREAMING_SNAKE_CASE , '''opt_state.msgpack''' ) , '''rb''' ) as f: snake_case__ : Optional[Any] =from_bytes(state.opt_state , f.read() ) snake_case__ : Dict =joblib.load(os.path.join(SCREAMING_SNAKE_CASE , '''args.joblib''' ) ) snake_case__ : Union[str, Any] =joblib.load(os.path.join(SCREAMING_SNAKE_CASE , '''data_collator.joblib''' ) ) with open(os.path.join(SCREAMING_SNAKE_CASE , '''training_state.json''' ) , '''r''' ) as f: snake_case__ : Tuple =json.load(SCREAMING_SNAKE_CASE ) snake_case__ : Tuple =training_state['''step'''] print('''DONE''' ) return params, opt_state, step, args, data_collator def lowercase_ ( SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Optional[Any] ): """simple docstring""" snake_case__ : Tuple =num_train_steps - warmup_steps snake_case__ : Union[str, Any] =optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE , end_value=SCREAMING_SNAKE_CASE , transition_steps=SCREAMING_SNAKE_CASE ) snake_case__ : Dict =optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE , end_value=1E-7 , transition_steps=SCREAMING_SNAKE_CASE ) snake_case__ : int =optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def lowercase_ ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Any , SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : Any ): """simple docstring""" def weight_decay_mask(SCREAMING_SNAKE_CASE : Tuple ): snake_case__ : Any =traverse_util.flatten_dict(SCREAMING_SNAKE_CASE ) snake_case__ : Optional[int] ={k: (v[-1] != '''bias''' and v[-2:] != ('''LayerNorm''', '''scale''')) for k, v in params.items()} return traverse_util.unflatten_dict(SCREAMING_SNAKE_CASE ) snake_case__ : Any =scheduler_fn(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) snake_case__ : List[str] =optax.adamw(learning_rate=SCREAMING_SNAKE_CASE , weight_decay=SCREAMING_SNAKE_CASE , mask=SCREAMING_SNAKE_CASE ) return tx, lr
408
0
def _a ( __lowercase ) -> bool: """simple docstring""" __UpperCamelCase = 0 for ch in input_str: __UpperCamelCase = ord(__lowercase ) __UpperCamelCase = pow(2 , __lowercase ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
383
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 lowerCAmelCase_ : """simple docstring""" def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.0_2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=None , ) -> Any: __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 = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __UpperCamelCase = (image_size // patch_size) ** 2 __UpperCamelCase = num_patches + 1 def __lowercase( self ) -> Optional[Any]: __UpperCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = self.get_config() return config, pixel_values, labels def __lowercase( self ) -> str: 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=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: __UpperCamelCase = TFViTModel(config=_SCREAMING_SNAKE_CASE ) __UpperCamelCase = model(_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) 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. __UpperCamelCase = self.image_size // 2 __UpperCamelCase = pixel_values[:, :, :image_size, :image_size] __UpperCamelCase = model(_SCREAMING_SNAKE_CASE , interpolate_pos_encoding=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) __UpperCamelCase = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def __lowercase( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: __UpperCamelCase = self.type_sequence_label_size __UpperCamelCase = TFViTForImageClassification(_SCREAMING_SNAKE_CASE ) __UpperCamelCase = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) 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. __UpperCamelCase = self.image_size // 2 __UpperCamelCase = pixel_values[:, :, :image_size, :image_size] __UpperCamelCase = model(_SCREAMING_SNAKE_CASE , interpolate_pos_encoding=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __UpperCamelCase = 1 __UpperCamelCase = TFViTForImageClassification(_SCREAMING_SNAKE_CASE ) __UpperCamelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __UpperCamelCase = model(_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self ) -> Dict: __UpperCamelCase = self.prepare_config_and_inputs() __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = config_and_inputs __UpperCamelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class lowerCAmelCase_ ( _lowercase , _lowercase , unittest.TestCase ): """simple docstring""" 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 __lowercase( self ) -> List[str]: __UpperCamelCase = TFViTModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def __lowercase( self ) -> int: self.config_tester.run_common_tests() @unittest.skip(reason='ViT does not use inputs_embeds' ) def __lowercase( self ) -> str: pass @unittest.skip(reason='ViT does not use inputs_embeds' ) def __lowercase( self ) -> Tuple: pass def __lowercase( self ) -> int: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) __UpperCamelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , tf.keras.layers.Layer ) ) def __lowercase( self ) -> Dict: __UpperCamelCase , __UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCamelCase = model_class(_SCREAMING_SNAKE_CASE ) __UpperCamelCase = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCamelCase = [*signature.parameters.keys()] __UpperCamelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def __lowercase( self ) -> str: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def __lowercase( self ) -> str: __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def __lowercase( self ) -> List[Any]: __UpperCamelCase = TFViTModel.from_pretrained('google/vit-base-patch16-224' ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def _a ( ) -> Optional[Any]: """simple docstring""" __UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class lowerCAmelCase_ ( unittest.TestCase ): """simple docstring""" @cached_property def __lowercase( self ) -> List[Any]: return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224' ) if is_vision_available() else None @slow def __lowercase( self ) -> Dict: __UpperCamelCase = TFViTForImageClassification.from_pretrained('google/vit-base-patch16-224' ) __UpperCamelCase = self.default_image_processor __UpperCamelCase = prepare_img() __UpperCamelCase = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors='tf' ) # forward pass __UpperCamelCase = model(**_SCREAMING_SNAKE_CASE ) # verify the logits __UpperCamelCase = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) __UpperCamelCase = 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] , _SCREAMING_SNAKE_CASE , atol=1e-4 )
383
1
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import TensorType, is_torch_available, logging UpperCAmelCase__ : Any = logging.get_logger(__name__) UpperCAmelCase__ : Dict = { 'Helsinki-NLP/opus-mt-en-de': 'https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/config.json', # See all Marian models at https://huggingface.co/models?filter=marian } class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : List[str] = '''marian''' __UpperCamelCase : str = ['''past_key_values'''] __UpperCamelCase : Optional[Any] = {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''} def __init__(self , SCREAMING_SNAKE_CASE__=5_81_01 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=10_24 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=40_96 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=40_96 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=10_24 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=5_81_00 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=5_81_00 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=0 , SCREAMING_SNAKE_CASE__=True , **SCREAMING_SNAKE_CASE__ , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = decoder_vocab_size or vocab_size SCREAMING_SNAKE_CASE__ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_model SCREAMING_SNAKE_CASE__ : int = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : Optional[Any] = encoder_layers SCREAMING_SNAKE_CASE__ : int = encoder_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : List[str] = decoder_layers SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_attention_heads SCREAMING_SNAKE_CASE__ : Any = dropout SCREAMING_SNAKE_CASE__ : str = attention_dropout SCREAMING_SNAKE_CASE__ : Dict = activation_dropout SCREAMING_SNAKE_CASE__ : Tuple = activation_function SCREAMING_SNAKE_CASE__ : List[str] = init_std SCREAMING_SNAKE_CASE__ : Optional[Any] = encoder_layerdrop SCREAMING_SNAKE_CASE__ : Tuple = decoder_layerdrop SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_cache SCREAMING_SNAKE_CASE__ : str = encoder_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE__ : Tuple = share_encoder_decoder_embeddings super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , is_encoder_decoder=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , forced_eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) class lowerCAmelCase_ (a__ ): """simple docstring""" @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.inputs def __magic_name__ (self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE__ : Any = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: SCREAMING_SNAKE_CASE__ : str = {0: """batch"""} SCREAMING_SNAKE_CASE__ : Any = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : List[Any] = {0: """batch""", 1: """decoder_sequence"""} SCREAMING_SNAKE_CASE__ : Tuple = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE__ , direction="""inputs""" ) elif self.task == "causal-lm": # TODO: figure this case out. SCREAMING_SNAKE_CASE__ : Optional[Any] = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: SCREAMING_SNAKE_CASE__ : Dict = self.num_layers for i in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[Any] = {0: """batch""", 2: """past_sequence + sequence"""} SCREAMING_SNAKE_CASE__ : Optional[Any] = {0: """batch""", 2: """past_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ : Optional[int] = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}), ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}), ] ) return common_inputs @property # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig.outputs def __magic_name__ (self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = super().outputs else: SCREAMING_SNAKE_CASE__ : Optional[int] = super(SCREAMING_SNAKE_CASE__ , self ).outputs if self.use_past: SCREAMING_SNAKE_CASE__ : List[Any] = self.num_layers for i in range(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Any = {0: """batch""", 2: """past_sequence + sequence"""} SCREAMING_SNAKE_CASE__ : List[str] = {0: """batch""", 2: """past_sequence + sequence"""} return common_outputs def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self._generate_dummy_inputs_for_encoder_and_decoder( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Generate decoder inputs SCREAMING_SNAKE_CASE__ : Optional[int] = seq_length if not self.use_past else 1 SCREAMING_SNAKE_CASE__ : Optional[int] = self._generate_dummy_inputs_for_encoder_and_decoder( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Tuple = {F'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()} SCREAMING_SNAKE_CASE__ : int = dict(**SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch SCREAMING_SNAKE_CASE__ : Union[str, Any] = common_inputs["""input_ids"""].shape SCREAMING_SNAKE_CASE__ : str = common_inputs["""decoder_input_ids"""].shape[1] SCREAMING_SNAKE_CASE__ : int = self.num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = decoder_seq_length + 3 SCREAMING_SNAKE_CASE__ : Optional[Any] = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat( [common_inputs["""decoder_attention_mask"""], torch.ones(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] , dim=1 ) SCREAMING_SNAKE_CASE__ : Any = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.num_layers SCREAMING_SNAKE_CASE__ : Any = min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) - min_num_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = """encoder""" if num_encoder_layers > num_decoder_layers else """decoder""" for _ in range(SCREAMING_SNAKE_CASE__ ): common_inputs["past_key_values"].append( ( torch.zeros(SCREAMING_SNAKE_CASE__ ), torch.zeros(SCREAMING_SNAKE_CASE__ ), torch.zeros(SCREAMING_SNAKE_CASE__ ), torch.zeros(SCREAMING_SNAKE_CASE__ ), ) ) # TODO: test this. SCREAMING_SNAKE_CASE__ : Dict = encoder_shape if remaining_side_name == """encoder""" else decoder_shape for _ in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): common_inputs["past_key_values"].append((torch.zeros(SCREAMING_SNAKE_CASE__ ), torch.zeros(SCREAMING_SNAKE_CASE__ )) ) return common_inputs def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self._generate_dummy_inputs_for_encoder_and_decoder( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch SCREAMING_SNAKE_CASE__ : Any = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE__ : Any = seqlen + 2 SCREAMING_SNAKE_CASE__ : List[Any] = self.num_layers SCREAMING_SNAKE_CASE__ : int = self.num_attention_heads SCREAMING_SNAKE_CASE__ : int = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) SCREAMING_SNAKE_CASE__ : List[str] = common_inputs["""attention_mask"""].dtype SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [common_inputs["""attention_mask"""], torch.ones(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ )] , dim=1 ) SCREAMING_SNAKE_CASE__ : List[str] = [ (torch.zeros(SCREAMING_SNAKE_CASE__ ), torch.zeros(SCREAMING_SNAKE_CASE__ )) for _ in range(SCREAMING_SNAKE_CASE__ ) ] return common_inputs def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = compute_effective_axis_dimension( SCREAMING_SNAKE_CASE__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.num_special_tokens_to_add(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = compute_effective_axis_dimension( SCREAMING_SNAKE_CASE__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=SCREAMING_SNAKE_CASE__ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE__ : Optional[int] = [""" """.join([tokenizer.unk_token] ) * seq_length] * batch_size SCREAMING_SNAKE_CASE__ : Optional[int] = dict(tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) ) return common_inputs def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = -1 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = None , ) -> Mapping[str, Any]: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE__ : Tuple = self._generate_dummy_inputs_for_default_and_seqaseq_lm( SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , seq_length=SCREAMING_SNAKE_CASE__ , is_pair=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = self._generate_dummy_inputs_for_causal_lm( SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , seq_length=SCREAMING_SNAKE_CASE__ , is_pair=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) return common_inputs def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" if self.task in ["default", "seq2seq-lm"]: SCREAMING_SNAKE_CASE__ : Optional[int] = super()._flatten_past_key_values_(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : List[str] = super(SCREAMING_SNAKE_CASE__ , self )._flatten_past_key_values_( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @property def __magic_name__ (self ) -> float: """simple docstring""" return 1E-4
704
"""simple docstring""" from __future__ import annotations import unittest from transformers import MobileBertConfig, is_tf_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_MODEL_FOR_PRETRAINING_MAPPING, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertModel, ) @require_tf class lowerCAmelCase_ (a__ , a__ , unittest.TestCase ): """simple docstring""" __UpperCamelCase : Any = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) __UpperCamelCase : Tuple = ( { '''feature-extraction''': TFMobileBertModel, '''fill-mask''': TFMobileBertForMaskedLM, '''question-answering''': TFMobileBertForQuestionAnswering, '''text-classification''': TFMobileBertForSequenceClassification, '''token-classification''': TFMobileBertForTokenClassification, '''zero-shot''': TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase : Optional[int] = False __UpperCamelCase : str = False def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = super()._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_labels=SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[str] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class lowerCAmelCase_ (a__ ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=13 , SCREAMING_SNAKE_CASE__=7 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=99 , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=32 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=37 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=0.1 , SCREAMING_SNAKE_CASE__=5_12 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=4 , SCREAMING_SNAKE_CASE__=None , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = seq_length SCREAMING_SNAKE_CASE__ : Any = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : List[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : str = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : Union[str, Any] = scope SCREAMING_SNAKE_CASE__ : Dict = embedding_size def __magic_name__ (self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Optional[Any] = MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , embedding_size=self.embedding_size , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFMobileBertModel(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} SCREAMING_SNAKE_CASE__ : List[Any] = model(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = [input_ids, input_mask] SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = TFMobileBertForMaskedLM(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} SCREAMING_SNAKE_CASE__ : List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFMobileBertForNextSentencePrediction(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} SCREAMING_SNAKE_CASE__ : List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = TFMobileBertForPreTraining(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual( result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.num_labels SCREAMING_SNAKE_CASE__ : List[Any] = TFMobileBertForSequenceClassification(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : str = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.num_choices SCREAMING_SNAKE_CASE__ : List[Any] = TFMobileBertForMultipleChoice(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ : Tuple = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, """token_type_ids""": multiple_choice_token_type_ids, } SCREAMING_SNAKE_CASE__ : Optional[int] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFMobileBertForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} SCREAMING_SNAKE_CASE__ : List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = TFMobileBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} SCREAMING_SNAKE_CASE__ : str = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __magic_name__ (self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict def __magic_name__ (self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = TFMobileBertModelTest.TFMobileBertModelTester(self ) SCREAMING_SNAKE_CASE__ : str = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def __magic_name__ (self ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() def __magic_name__ (self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def __magic_name__ (self ) -> List[str]: """simple docstring""" for model_name in ["google/mobilebert-uncased"]: SCREAMING_SNAKE_CASE__ : Optional[Any] = TFMobileBertModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_tf class lowerCAmelCase_ (unittest.TestCase ): """simple docstring""" @slow def __magic_name__ (self ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = TFMobileBertForPreTraining.from_pretrained("""google/mobilebert-uncased""" ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ : Dict = model(SCREAMING_SNAKE_CASE__ )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = [1, 6, 3_05_22] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.constant( [ [ [-4.5919547, -9.248295, -9.645256], [-6.7306175, -6.440284, -6.6052837], [-7.2743506, -6.7847915, -6.024673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1E-4 )
545
0
'''simple docstring''' from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass a : Union[str, Any] = (3, 9, -11, 0, 7, 5, 1, -1) a : Tuple = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class UpperCamelCase__ : """simple docstring""" SCREAMING_SNAKE_CASE__ : int SCREAMING_SNAKE_CASE__ : Node | None class UpperCamelCase__ : """simple docstring""" def __init__( self , snake_case ): '''simple docstring''' UpperCAmelCase : Node | None = None for i in sorted(snake_case , reverse=snake_case ): UpperCAmelCase : List[str] = Node(snake_case , self.head ) def __iter__( self ): '''simple docstring''' UpperCAmelCase : Any = self.head while node: yield node.data UpperCAmelCase : Dict = node.next_node def __len__( self ): '''simple docstring''' return sum(1 for _ in self ) def __str__( self ): '''simple docstring''' return " -> ".join([str(snake_case ) for node in self] ) def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' return SortedLinkedList(list(__magic_name__ ) + list(__magic_name__ ) ) if __name__ == "__main__": import doctest doctest.testmod() a : Union[str, Any] = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
679
'''simple docstring''' import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def lowercase ( __magic_name__="" ): '''simple docstring''' UpperCAmelCase : Dict = tempfile.mkdtemp() return os.path.join(__magic_name__ , str(uuid.uuida() ) + suffix ) @require_soundfile @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def A_ ( self ): '''simple docstring''' UpperCAmelCase : Any = torch.rand(1_2 , dtype=torch.floataa ) - 0.5 UpperCAmelCase : int = AgentAudio(snake_case ) UpperCAmelCase : str = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(snake_case , agent_type.to_raw() , atol=1e-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(snake_case ) ) # Ensure that the file contains the same value as the original tensor UpperCAmelCase , UpperCAmelCase : str = sf.read(snake_case ) self.assertTrue(torch.allclose(snake_case , torch.tensor(snake_case ) , atol=1e-4 ) ) def A_ ( self ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = torch.rand(1_2 , dtype=torch.floataa ) - 0.5 UpperCAmelCase : Any = get_new_path(suffix=".wav" ) sf.write(snake_case , snake_case , 1_6_0_0_0 ) UpperCAmelCase : Optional[Any] = AgentAudio(snake_case ) self.assertTrue(torch.allclose(snake_case , agent_type.to_raw() , atol=1e-4 ) ) self.assertEqual(agent_type.to_string() , snake_case ) @require_vision @require_torch class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def A_ ( self ): '''simple docstring''' UpperCAmelCase : Optional[Any] = torch.randint(0 , 2_5_6 , (6_4, 6_4, 3) ) UpperCAmelCase : Tuple = AgentImage(snake_case ) UpperCAmelCase : Tuple = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(snake_case , agent_type._tensor , atol=1e-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(snake_case ) ) def A_ ( self ): '''simple docstring''' UpperCAmelCase : Optional[Any] = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" UpperCAmelCase : Any = Image.open(snake_case ) UpperCAmelCase : List[str] = AgentImage(snake_case ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(snake_case ) ) def A_ ( self ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" UpperCAmelCase : Dict = Image.open(snake_case ) UpperCAmelCase : int = AgentImage(snake_case ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(snake_case ) ) class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" def A_ ( self ): '''simple docstring''' UpperCAmelCase : Any = "Hey!" UpperCAmelCase : Tuple = AgentText(snake_case ) self.assertEqual(snake_case , agent_type.to_string() ) self.assertEqual(snake_case , agent_type.to_raw() ) self.assertEqual(snake_case , snake_case )
679
1
from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging _UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = ['input_features', 'attention_mask'] def __init__( self , snake_case_=80 , snake_case_=1_60_00 , snake_case_=0.0 , snake_case_=10 , snake_case_=25 , snake_case_="hamming_window" , snake_case_=3_27_68.0 , snake_case_=0.97 , snake_case_=1.0 , snake_case_=True , snake_case_=True , snake_case_=False , **snake_case_ , ): super().__init__(feature_size=snake_case_ , sampling_rate=snake_case_ , padding_value=snake_case_ , **snake_case_ ) lowercase =feature_size lowercase =sampling_rate lowercase =padding_value lowercase =hop_length lowercase =win_length lowercase =frame_signal_scale lowercase =preemphasis_coeff lowercase =mel_floor lowercase =normalize_means lowercase =normalize_vars lowercase =win_function lowercase =return_attention_mask lowercase =win_length * sampling_rate // 10_00 lowercase =hop_length * sampling_rate // 10_00 lowercase =optimal_fft_length(self.sample_size ) lowercase =(self.n_fft // 2) + 1 def _A( self , snake_case_ ): if self.win_function == "hamming_window": lowercase =window_function(window_length=self.sample_size , name=self.win_function , periodic=snake_case_ ) else: lowercase =window_function(window_length=self.sample_size , name=self.win_function ) lowercase =mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) lowercase =spectrogram( one_waveform * self.frame_signal_scale , window=snake_case_ , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=snake_case_ , preemphasis=self.preemphasis_coeff , mel_filters=snake_case_ , mel_floor=self.mel_floor , log_mel='''log''' , ) return msfc_features.T def _A( self , snake_case_ , snake_case_ , snake_case_ ): # make sure we normalize float32 arrays if self.normalize_means: lowercase =x[:input_length].mean(axis=0 ) lowercase =np.subtract(snake_case_ , snake_case_ ) if self.normalize_vars: lowercase =x[:input_length].std(axis=0 ) lowercase =np.divide(snake_case_ , snake_case_ ) if input_length < x.shape[0]: lowercase =padding_value # make sure array is in float32 lowercase =x.astype(np.floataa ) return x def _A( self , snake_case_ , snake_case_ = None ): lowercase =attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(snake_case_ , snake_case_ , self.padding_value ) for x, n in zip(snake_case_ , snake_case_ )] def __call__( self , snake_case_ , snake_case_ = False , snake_case_ = None , snake_case_ = False , snake_case_ = None , snake_case_ = None , snake_case_ = None , snake_case_ = None , **snake_case_ , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( '''It is strongly recommended to pass the ``sampling_rate`` argument to this function. ''' '''Failing to do so can result in silent errors that might be hard to debug.''' ) lowercase =isinstance(snake_case_ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) lowercase =is_batched_numpy or ( isinstance(snake_case_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: lowercase =[np.asarray(snake_case_ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(snake_case_ , np.ndarray ): lowercase =np.asarray(snake_case_ , dtype=np.floataa ) elif isinstance(snake_case_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): lowercase =raw_speech.astype(np.floataa ) # always return batch if not is_batched: lowercase =[raw_speech] # extract fbank features lowercase =[self._extract_mfsc_features(snake_case_ ) for one_waveform in raw_speech] # convert into correct format for padding lowercase =BatchFeature({'''input_features''': features} ) lowercase =self.pad( snake_case_ , padding=snake_case_ , max_length=snake_case_ , truncation=snake_case_ , pad_to_multiple_of=snake_case_ , return_attention_mask=snake_case_ , **snake_case_ , ) # make sure list is in array format lowercase =padded_inputs.get('''input_features''' ) if isinstance(input_features[0] , snake_case_ ): lowercase =[np.asarray(snake_case_ , dtype=np.floataa ) for feature in input_features] lowercase =padded_inputs.get('''attention_mask''' ) if attention_mask is not None: lowercase =[np.asarray(snake_case_ , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: lowercase =( np.array(snake_case_ , dtype=np.intaa ) if self._get_padding_strategies(snake_case_ , max_length=snake_case_ ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) lowercase =self.normalize( padded_inputs['''input_features'''] , attention_mask=snake_case_ ) if return_tensors is not None: lowercase =padded_inputs.convert_to_tensors(snake_case_ ) return padded_inputs
702
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCAmelCase : List[str] = logging.get_logger(__name__) _UpperCAmelCase : str = { '''google/pix2struct-textcaps-base''': ( '''https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json''' ), } class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct_text_model' UpperCamelCase__ = ['past_key_values'] UpperCamelCase__ = { 'hidden_size': 'hidden_size', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self , snake_case_=5_02_44 , snake_case_=7_68 , snake_case_=64 , snake_case_=20_48 , snake_case_=12 , snake_case_=12 , snake_case_=32 , snake_case_=1_28 , snake_case_=0.1 , snake_case_=1E-6 , snake_case_=1.0 , snake_case_="gelu_new" , snake_case_=0 , snake_case_=False , snake_case_=0 , snake_case_=1 , snake_case_=False , snake_case_=True , **snake_case_ , ): lowercase =vocab_size lowercase =hidden_size lowercase =d_kv lowercase =d_ff lowercase =num_layers lowercase =num_heads lowercase =relative_attention_num_buckets lowercase =relative_attention_max_distance lowercase =dropout_rate lowercase =layer_norm_epsilon lowercase =initializer_factor lowercase =use_cache lowercase =eos_token_id lowercase =decoder_start_token_id # for backwards compatibility lowercase =dense_act_fn super().__init__( pad_token_id=snake_case_ , eos_token_id=snake_case_ , decoder_start_token_id=snake_case_ , tie_word_embeddings=snake_case_ , is_decoder=snake_case_ , **snake_case_ , ) @classmethod def _A( cls , snake_case_ , **snake_case_ ): cls._set_token_in_kwargs(snake_case_ ) lowercase , lowercase =cls.get_config_dict(snake_case_ , **snake_case_ ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase =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(snake_case_ , **snake_case_ ) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct_vision_model' def __init__( self , snake_case_=7_68 , snake_case_=7_68 , snake_case_=20_48 , snake_case_=64 , snake_case_=12 , snake_case_=12 , snake_case_="gelu_new" , snake_case_=1E-6 , snake_case_=0.0 , snake_case_=0.0 , snake_case_=1E-10 , snake_case_=1.0 , snake_case_=40_96 , snake_case_=32 , snake_case_=1_28 , **snake_case_ , ): super().__init__(**snake_case_ ) lowercase =hidden_size lowercase =patch_embed_hidden_size lowercase =d_ff lowercase =dropout_rate lowercase =num_hidden_layers lowercase =num_attention_heads lowercase =initializer_range lowercase =initializer_factor lowercase =attention_dropout lowercase =layer_norm_eps lowercase =dense_act_fn lowercase =seq_len lowercase =relative_attention_num_buckets lowercase =relative_attention_max_distance lowercase =d_kv @classmethod def _A( cls , snake_case_ , **snake_case_ ): cls._set_token_in_kwargs(snake_case_ ) lowercase , lowercase =cls.get_config_dict(snake_case_ , **snake_case_ ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get('''model_type''' ) == "pix2struct": lowercase =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(snake_case_ , **snake_case_ ) class __magic_name__ ( __SCREAMING_SNAKE_CASE ): UpperCamelCase__ = 'pix2struct' UpperCamelCase__ = True def __init__( self , snake_case_=None , snake_case_=None , snake_case_=1.0 , snake_case_=0.02 , snake_case_=False , snake_case_=False , snake_case_=True , **snake_case_ , ): super().__init__(tie_word_embeddings=snake_case_ , is_encoder_decoder=snake_case_ , **snake_case_ ) if text_config is None: lowercase ={} logger.info('''text_config is None. Initializing the Pix2StructTextConfig with default values.''' ) if vision_config is None: lowercase ={} logger.info('''vision_config is None. Initializing the Pix2StructVisionConfig with default values.''' ) lowercase =PixaStructTextConfig(**snake_case_ ) lowercase =PixaStructVisionConfig(**snake_case_ ) lowercase =self.text_config.decoder_start_token_id lowercase =self.text_config.pad_token_id lowercase =self.text_config.eos_token_id lowercase =initializer_factor lowercase =initializer_range lowercase =self.initializer_range lowercase =self.initializer_range lowercase =is_vqa @classmethod def _A( cls , snake_case_ , snake_case_ , **snake_case_ ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **snake_case_ ) def _A( self ): lowercase =copy.deepcopy(self.__dict__ ) lowercase =self.text_config.to_dict() lowercase =self.vision_config.to_dict() lowercase =self.__class__.model_type return output
145
0
'''simple docstring''' import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class a_ ( UpperCamelCase__ ): lowerCamelCase__ : Optional[int] = 'Speech2TextFeatureExtractor' lowerCamelCase__ : Dict = 'Speech2TextTokenizer' def __init__( self , UpperCAmelCase , UpperCAmelCase ): super().__init__(UpperCAmelCase , UpperCAmelCase ) a_ = self.feature_extractor a_ = False def __call__( self , *UpperCAmelCase , **UpperCAmelCase ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*UpperCAmelCase , **UpperCAmelCase ) if "raw_speech" in kwargs: warnings.warn("""Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.""" ) a_ = kwargs.pop("""raw_speech""" ) else: a_ = kwargs.pop("""audio""" , UpperCAmelCase ) a_ = kwargs.pop("""sampling_rate""" , UpperCAmelCase ) a_ = kwargs.pop("""text""" , UpperCAmelCase ) if len(UpperCAmelCase ) > 0: a_ = args[0] a_ = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if audio is not None: a_ = self.feature_extractor(UpperCAmelCase , *UpperCAmelCase , sampling_rate=UpperCAmelCase , **UpperCAmelCase ) if text is not None: a_ = self.tokenizer(UpperCAmelCase , **UpperCAmelCase ) if text is None: return inputs elif audio is None: return encodings else: a_ = encodings["""input_ids"""] return inputs def lowerCAmelCase__ ( self , *UpperCAmelCase , **UpperCAmelCase ): return self.tokenizer.batch_decode(*UpperCAmelCase , **UpperCAmelCase ) def lowerCAmelCase__ ( self , *UpperCAmelCase , **UpperCAmelCase ): return self.tokenizer.decode(*UpperCAmelCase , **UpperCAmelCase ) @contextmanager def lowerCAmelCase__ ( self ): warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your audio inputs, or in a separate call.""" ) a_ = True a_ = self.tokenizer yield a_ = self.feature_extractor a_ = False
263
'''simple docstring''' import requests lowercase__ ='' # <-- Put your OpenWeatherMap appid here! lowercase__ ='https://api.openweathermap.org/data/2.5/' def UpperCamelCase_ ( A__ = "Chicago" , A__ = APPID ): return requests.get(URL_BASE + """weather""" , params=locals() ).json() def UpperCamelCase_ ( A__ = "Kolkata, India" , A__ = APPID ): return requests.get(URL_BASE + """forecast""" , params=locals() ).json() def UpperCamelCase_ ( 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: lowercase__ =input('Enter a location:').strip() if location: pprint(current_weather(location)) else: break
263
1
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class __snake_case : '''simple docstring''' def _a ( self ): torch.manual_seed(0 ) a__ = TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) a__ = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) a__ = 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 ) a__ = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_001 , beta_end=0.02 , thresholding=a_ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , ) torch.manual_seed(0 ) a__ = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def _a ( self ): torch.manual_seed(0 ) a__ = TaEncoderModel.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) a__ = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-t5""" ) torch.manual_seed(0 ) a__ = 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.414 , time_embedding_act_fn="""gelu""" , time_embedding_dim=32 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) a__ = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_001 , beta_end=0.02 , thresholding=a_ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type="""epsilon""" , variance_type="""learned_range""" , ) torch.manual_seed(0 ) a__ = DDPMScheduler( num_train_timesteps=1_000 , beta_schedule="""squaredcos_cap_v2""" , beta_start=0.0_001 , beta_end=0.02 , ) torch.manual_seed(0 ) a__ = 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 _a ( self ): a__ = self.get_dummy_components() a__ = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) a__ = self.get_dummy_inputs(a_ ) a__ = inputs["""prompt"""] a__ = inputs["""generator"""] a__ = inputs["""num_inference_steps"""] a__ = inputs["""output_type"""] if "image" in inputs: a__ = inputs["""image"""] else: a__ = None if "mask_image" in inputs: a__ = inputs["""mask_image"""] else: a__ = None if "original_image" in inputs: a__ = inputs["""original_image"""] else: a__ = None a__ , a__ = pipe.encode_prompt(a_ ) # inputs with prompt converted to embeddings a__ = { """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: a__ = image if mask_image is not None: a__ = mask_image if original_image is not None: a__ = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(a_ , a_ , a_ ) a__ = pipe(**a_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a_ ) a__ = self.pipeline_class.from_pretrained(a_ ) pipe_loaded.to(a_ ) pipe_loaded.set_progress_bar_config(disable=a_ ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(a_ , a_ ) is None , F'''`{optional_component}` did not stay set to None after loading.''' , ) a__ = self.get_dummy_inputs(a_ ) a__ = inputs["""generator"""] a__ = inputs["""num_inference_steps"""] a__ = inputs["""output_type"""] # inputs with prompt converted to embeddings a__ = { """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: a__ = image if mask_image is not None: a__ = mask_image if original_image is not None: a__ = original_image a__ = pipe_loaded(**a_ )[0] a__ = np.abs(to_np(a_ ) - to_np(a_ ) ).max() self.assertLess(a_ , 1E-4 ) def _a ( self ): a__ = self.get_dummy_components() a__ = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) a__ = self.get_dummy_inputs(a_ ) a__ = pipe(**a_ )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(a_ ) a__ = self.pipeline_class.from_pretrained(a_ ) pipe_loaded.to(a_ ) pipe_loaded.set_progress_bar_config(disable=a_ ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests a__ = self.get_dummy_inputs(a_ ) a__ = pipe_loaded(**a_ )[0] a__ = np.abs(to_np(a_ ) - to_np(a_ ) ).max() self.assertLess(a_ , 1E-4 )
701
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError("""At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training""") # TF training parameters UpperCAmelCase = False UpperCAmelCase = False def A_ ( __a : Namespace ): """simple docstring""" return TrainCommand(__a ) class __snake_case ( SCREAMING_SNAKE_CASE): '''simple docstring''' @staticmethod def _a ( a_ ): a__ = parser.add_parser("""train""" , help="""CLI tool to train a model on a task.""" ) train_parser.add_argument( """--train_data""" , type=a_ , required=a_ , help="""path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.""" , ) train_parser.add_argument( """--column_label""" , type=a_ , default=0 , help="""Column of the dataset csv file with example labels.""" ) train_parser.add_argument( """--column_text""" , type=a_ , default=1 , help="""Column of the dataset csv file with example texts.""" ) train_parser.add_argument( """--column_id""" , type=a_ , default=2 , help="""Column of the dataset csv file with example ids.""" ) train_parser.add_argument( """--skip_first_row""" , action="""store_true""" , help="""Skip the first row of the csv file (headers).""" ) train_parser.add_argument("""--validation_data""" , type=a_ , default="""""" , help="""path to validation dataset.""" ) train_parser.add_argument( """--validation_split""" , type=a_ , default=0.1 , help="""if validation dataset is not provided, fraction of train dataset to use as validation dataset.""" , ) train_parser.add_argument("""--output""" , type=a_ , default="""./""" , help="""path to saved the trained model.""" ) train_parser.add_argument( """--task""" , type=a_ , default="""text_classification""" , help="""Task to train the model on.""" ) train_parser.add_argument( """--model""" , type=a_ , default="""bert-base-uncased""" , help="""Model's name or path to stored model.""" ) train_parser.add_argument("""--train_batch_size""" , type=a_ , default=32 , help="""Batch size for training.""" ) train_parser.add_argument("""--valid_batch_size""" , type=a_ , default=64 , help="""Batch size for validation.""" ) train_parser.add_argument("""--learning_rate""" , type=a_ , default=3E-5 , help="""Learning rate.""" ) train_parser.add_argument("""--adam_epsilon""" , type=a_ , default=1E-0_8 , help="""Epsilon for Adam optimizer.""" ) train_parser.set_defaults(func=a_ ) def __init__( self , a_ ): a__ = logging.get_logger("""transformers-cli/training""" ) a__ = """tf""" if is_tf_available() else """torch""" os.makedirs(args.output , exist_ok=a_ ) a__ = args.output a__ = args.column_label a__ = args.column_text a__ = args.column_id self.logger.info(F'''Loading {args.task} pipeline for {args.model}''' ) if args.task == "text_classification": a__ = TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(F'''Loading dataset from {args.train_data}''' ) a__ = Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) a__ = None if args.validation_data: self.logger.info(F'''Loading validation dataset from {args.validation_data}''' ) a__ = Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) a__ = args.validation_split a__ = args.train_batch_size a__ = args.valid_batch_size a__ = args.learning_rate a__ = args.adam_epsilon def _a ( self ): if self.framework == "tf": return self.run_tf() return self.run_torch() def _a ( self ): raise NotImplementedError def _a ( self ): self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
351
0
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device _lowerCamelCase = False class snake_case ( unittest.TestCase ): pass @nightly @require_torch_gpu class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) __SCREAMING_SNAKE_CASE : List[str] = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = pipe.dual_guided( prompt='''first prompt''' , image=_lowerCamelCase , text_to_image_strength=0.7_5 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = VersatileDiffusionPipeline.from_pretrained(_lowerCamelCase , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = generator.manual_seed(0 ) __SCREAMING_SNAKE_CASE : int = pipe.dual_guided( prompt='''first prompt''' , image=_lowerCamelCase , text_to_image_strength=0.7_5 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = '''cyberpunk 2077''' __SCREAMING_SNAKE_CASE : Any = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) __SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = pipe.dual_guided( prompt=_lowerCamelCase , image=_lowerCamelCase , text_to_image_strength=0.7_5 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' , ).images __SCREAMING_SNAKE_CASE : List[Any] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : List[str] = np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 __SCREAMING_SNAKE_CASE : List[str] = '''A painting of a squirrel eating a burger ''' __SCREAMING_SNAKE_CASE : str = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE : Dict = pipe.text_to_image( prompt=_lowerCamelCase , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' ).images __SCREAMING_SNAKE_CASE : Any = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : List[Any] = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 __SCREAMING_SNAKE_CASE : str = pipe.image_variation(_lowerCamelCase , generator=_lowerCamelCase , output_type='''numpy''' ).images __SCREAMING_SNAKE_CASE : List[Any] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) __SCREAMING_SNAKE_CASE : Tuple = np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
674
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
1
'''simple docstring''' import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): lowercase_ : Optional[int] = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): lowercase_ : Optional[Any] = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: lowercase_ : List[str] = s_dict.pop(SCREAMING_SNAKE_CASE_ ) elif "subsample" in key: lowercase_ : List[Any] = s_dict.pop(SCREAMING_SNAKE_CASE_ ) def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): lowercase_ ,lowercase_ : Any = emb.weight.shape lowercase_ : Dict = nn.Linear(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , bias=SCREAMING_SNAKE_CASE_ ) lowercase_ : Any = emb.weight.data return lin_layer def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): lowercase_ : Any = torch.load(SCREAMING_SNAKE_CASE_ , map_location='cpu' ) lowercase_ : List[Any] = mam_aaa['args'] lowercase_ : List[Any] = mam_aaa['model'] lowercase_ : Optional[int] = state_dict['decoder.output_projection.weight'] remove_ignore_keys_(SCREAMING_SNAKE_CASE_ ) rename_keys(SCREAMING_SNAKE_CASE_ ) lowercase_ : Any = state_dict['decoder.embed_tokens.weight'].shape[0] lowercase_ : str = args.share_decoder_input_output_embed lowercase_ : Tuple = [int(SCREAMING_SNAKE_CASE_ ) for i in args.conv_kernel_sizes.split(',' )] lowercase_ : Union[str, Any] = SpeechaTextConfig( vocab_size=SCREAMING_SNAKE_CASE_ , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , num_conv_layers=len(SCREAMING_SNAKE_CASE_ ) , conv_channels=args.conv_channels , conv_kernel_sizes=SCREAMING_SNAKE_CASE_ , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=SCREAMING_SNAKE_CASE_ , num_beams=5 , max_length=200 , use_cache=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=2 , early_stopping=SCREAMING_SNAKE_CASE_ , ) lowercase_ : List[Any] = SpeechaTextForConditionalGeneration(SCREAMING_SNAKE_CASE_ ) lowercase_ ,lowercase_ : List[Any] = model.model.load_state_dict(SCREAMING_SNAKE_CASE_ , strict=SCREAMING_SNAKE_CASE_ ) if len(SCREAMING_SNAKE_CASE_ ) > 0 and not set(SCREAMING_SNAKE_CASE_ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( 'Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,' f''' but all the following weights are missing {missing}''' ) if tie_embeds: lowercase_ : int = make_linear_from_emb(model.model.decoder.embed_tokens ) else: lowercase_ : List[str] = lm_head_weights model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') _A = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
438
'''simple docstring''' import argparse import json from pathlib import Path import torch import torchaudio from datasets import load_dataset from huggingface_hub import hf_hub_download from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification from transformers.utils import logging logging.set_verbosity_info() _A = logging.get_logger(__name__) def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): lowercase_ : List[Any] = ASTConfig() if "10-10" in model_name: pass elif "speech-commands" in model_name: lowercase_ : List[Any] = 128 elif "12-12" in model_name: lowercase_ : Tuple = 12 lowercase_ : List[Any] = 12 elif "14-14" in model_name: lowercase_ : List[str] = 14 lowercase_ : Optional[Any] = 14 elif "16-16" in model_name: lowercase_ : Union[str, Any] = 16 lowercase_ : List[str] = 16 else: raise ValueError('Model not supported' ) lowercase_ : Optional[Any] = 'huggingface/label-files' if "speech-commands" in model_name: lowercase_ : List[str] = 35 lowercase_ : int = 'speech-commands-v2-id2label.json' else: lowercase_ : Union[str, Any] = 527 lowercase_ : int = 'audioset-id2label.json' lowercase_ : Union[str, Any] = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type='dataset' ) , 'r' ) ) lowercase_ : Union[str, Any] = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} lowercase_ : Optional[int] = idalabel lowercase_ : Optional[int] = {v: k for k, v in idalabel.items()} return config def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): if "module.v" in name: lowercase_ : Dict = name.replace('module.v' , 'audio_spectrogram_transformer' ) if "cls_token" in name: lowercase_ : Optional[Any] = name.replace('cls_token' , 'embeddings.cls_token' ) if "dist_token" in name: lowercase_ : Any = name.replace('dist_token' , 'embeddings.distillation_token' ) if "pos_embed" in name: lowercase_ : List[str] = name.replace('pos_embed' , 'embeddings.position_embeddings' ) if "patch_embed.proj" in name: lowercase_ : int = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) # transformer blocks if "blocks" in name: lowercase_ : Optional[Any] = name.replace('blocks' , 'encoder.layer' ) if "attn.proj" in name: lowercase_ : Optional[int] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: lowercase_ : Dict = name.replace('attn' , 'attention.self' ) if "norm1" in name: lowercase_ : int = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: lowercase_ : Optional[int] = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: lowercase_ : Optional[int] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: lowercase_ : int = name.replace('mlp.fc2' , 'output.dense' ) # final layernorm if "audio_spectrogram_transformer.norm" in name: lowercase_ : int = name.replace('audio_spectrogram_transformer.norm' , 'audio_spectrogram_transformer.layernorm' ) # classifier head if "module.mlp_head.0" in name: lowercase_ : Dict = name.replace('module.mlp_head.0' , 'classifier.layernorm' ) if "module.mlp_head.1" in name: lowercase_ : List[Any] = name.replace('module.mlp_head.1' , 'classifier.dense' ) return name def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): for key in orig_state_dict.copy().keys(): lowercase_ : List[str] = orig_state_dict.pop(SCREAMING_SNAKE_CASE_ ) if "qkv" in key: lowercase_ : List[str] = key.split('.' ) lowercase_ : int = int(key_split[3] ) lowercase_ : Tuple = config.hidden_size if "weight" in key: lowercase_ : Tuple = val[:dim, :] lowercase_ : Union[str, Any] = val[dim : dim * 2, :] lowercase_ : Optional[int] = val[-dim:, :] else: lowercase_ : Optional[Any] = val[:dim] lowercase_ : Any = val[dim : dim * 2] lowercase_ : Tuple = val[-dim:] else: lowercase_ : Optional[Any] = val return orig_state_dict def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ ): lowercase_ : List[Any] = [ 'module.v.head.weight', 'module.v.head.bias', 'module.v.head_dist.weight', 'module.v.head_dist.bias', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @torch.no_grad() def _UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): lowercase_ : Dict = get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE_ ) lowercase_ : Optional[int] = { 'ast-finetuned-audioset-10-10-0.4593': ( 'https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1' ), 'ast-finetuned-audioset-10-10-0.450': ( 'https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1' ), 'ast-finetuned-audioset-10-10-0.448': ( 'https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1' ), 'ast-finetuned-audioset-10-10-0.448-v2': ( 'https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1' ), 'ast-finetuned-audioset-12-12-0.447': ( 'https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1' ), 'ast-finetuned-audioset-14-14-0.443': ( 'https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1' ), 'ast-finetuned-audioset-16-16-0.442': ( 'https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1' ), 'ast-finetuned-speech-commands-v2': ( 'https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1' ), } # load original state_dict lowercase_ : Dict = model_name_to_url[model_name] lowercase_ : Optional[Any] = torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE_ , map_location='cpu' ) # remove some keys remove_keys(SCREAMING_SNAKE_CASE_ ) # rename some keys lowercase_ : str = convert_state_dict(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # load 🤗 model lowercase_ : Optional[Any] = ASTForAudioClassification(SCREAMING_SNAKE_CASE_ ) model.eval() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # verify outputs on dummy input # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62 lowercase_ : Tuple = -4.267_7393 if 'speech-commands' not in model_name else -6.84_5978 lowercase_ : str = 4.568_9974 if 'speech-commands' not in model_name else 5.565_4526 lowercase_ : str = 1_024 if 'speech-commands' not in model_name else 128 lowercase_ : Dict = ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) if "speech-commands" in model_name: lowercase_ : Optional[Any] = load_dataset('speech_commands' , 'v0.02' , split='validation' ) lowercase_ : Any = dataset[0]['audio']['array'] else: lowercase_ : Any = hf_hub_download( repo_id='nielsr/audio-spectogram-transformer-checkpoint' , filename='sample_audio.flac' , repo_type='dataset' , ) lowercase_ ,lowercase_ : Union[str, Any] = torchaudio.load(SCREAMING_SNAKE_CASE_ ) lowercase_ : str = waveform.squeeze().numpy() lowercase_ : str = feature_extractor(SCREAMING_SNAKE_CASE_ , sampling_rate=16_000 , return_tensors='pt' ) # forward pass lowercase_ : Tuple = model(**SCREAMING_SNAKE_CASE_ ) lowercase_ : Tuple = outputs.logits if model_name == "ast-finetuned-audioset-10-10-0.4593": lowercase_ : int = torch.tensor([-0.8760, -7.0042, -8.6602] ) elif model_name == "ast-finetuned-audioset-10-10-0.450": lowercase_ : Optional[int] = torch.tensor([-1.1986, -7.0903, -8.2718] ) elif model_name == "ast-finetuned-audioset-10-10-0.448": lowercase_ : Optional[Any] = torch.tensor([-2.6128, -8.0080, -9.4344] ) elif model_name == "ast-finetuned-audioset-10-10-0.448-v2": lowercase_ : List[str] = torch.tensor([-1.5080, -7.4534, -8.8917] ) elif model_name == "ast-finetuned-audioset-12-12-0.447": lowercase_ : List[str] = torch.tensor([-0.5050, -6.5833, -8.0843] ) elif model_name == "ast-finetuned-audioset-14-14-0.443": lowercase_ : Any = torch.tensor([-0.3826, -7.0336, -8.2413] ) elif model_name == "ast-finetuned-audioset-16-16-0.442": lowercase_ : List[str] = torch.tensor([-1.2113, -6.9101, -8.3470] ) elif model_name == "ast-finetuned-speech-commands-v2": lowercase_ : Optional[Any] = torch.tensor([6.1589, -8.0566, -8.7984] ) else: raise ValueError('Unknown model name' ) if not torch.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ): raise ValueError('Logits don\'t match' ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) print(f'''Saving feature extractor to {pytorch_dump_folder_path}''' ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if push_to_hub: print('Pushing model and feature extractor to the hub...' ) model.push_to_hub(f'''MIT/{model_name}''' ) feature_extractor.push_to_hub(f'''MIT/{model_name}''' ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='ast-finetuned-audioset-10-10-0.4593', type=str, help='Name of the Audio Spectrogram Transformer model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) _A = parser.parse_args() convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
438
1
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": lowercase_ = argparse.ArgumentParser( description=( "Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned" " Distillation" ) ) parser.add_argument("--model_type", default="bert", choices=["bert"]) parser.add_argument("--model_name", default="bert-base-uncased", type=str) parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_bert-base-uncased_0247911.pth", type=str) parser.add_argument("--vocab_transform", action="store_true") lowercase_ = parser.parse_args() if args.model_type == "bert": lowercase_ = BertForMaskedLM.from_pretrained(args.model_name) lowercase_ = "bert" else: raise ValueError("args.model_type should be \"bert\".") lowercase_ = model.state_dict() lowercase_ = {} for w in ["word_embeddings", "position_embeddings"]: lowercase_ = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: lowercase_ = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] lowercase_ = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: lowercase_ = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] lowercase_ = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] lowercase_ = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] lowercase_ = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] lowercase_ = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] lowercase_ = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] lowercase_ = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] lowercase_ = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 lowercase_ = state_dict["cls.predictions.decoder.weight"] lowercase_ = state_dict["cls.predictions.bias"] if args.vocab_transform: for w in ["weight", "bias"]: lowercase_ = state_dict[f"""cls.predictions.transform.dense.{w}"""] lowercase_ = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
470
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class UpperCAmelCase_ (lowerCamelCase_ ): """simple docstring""" def __init__( self : List[Any] , a_ : str = "▁" , a_ : bool = True , a_ : Union[str, AddedToken] = "<unk>" , a_ : Union[str, AddedToken] = "</s>" , a_ : Union[str, AddedToken] = "<pad>" , )-> List[Any]: """simple docstring""" UpperCAmelCase_ : Dict = { """pad""": {"""id""": 0, """token""": pad_token}, """eos""": {"""id""": 1, """token""": eos_token}, """unk""": {"""id""": 2, """token""": unk_token}, } UpperCAmelCase_ : Dict = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): UpperCAmelCase_ : Optional[int] = token_dict["""token"""] UpperCAmelCase_ : Tuple = Tokenizer(Unigram() ) UpperCAmelCase_ : Optional[Any] = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(""" {2,}""" ) , """ """ ), normalizers.Lowercase(), ] ) UpperCAmelCase_ : Any = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=a_ , add_prefix_space=a_ ), pre_tokenizers.Digits(individual_digits=a_ ), pre_tokenizers.Punctuation(), ] ) UpperCAmelCase_ : str = decoders.Metaspace(replacement=a_ , add_prefix_space=a_ ) UpperCAmelCase_ : List[Any] = TemplateProcessing( single=f'''$A {self.special_tokens['eos']['token']}''' , special_tokens=[(self.special_tokens["""eos"""]["""token"""], self.special_tokens["""eos"""]["""id"""])] , ) UpperCAmelCase_ : Dict = { """model""": """SentencePieceUnigram""", """replacement""": replacement, """add_prefix_space""": add_prefix_space, } super().__init__(a_ , a_ ) def a ( self : int , a_ : Union[str, List[str]] , a_ : int = 80_00 , a_ : bool = True , )-> int: """simple docstring""" UpperCAmelCase_ : int = trainers.UnigramTrainer( vocab_size=a_ , special_tokens=self.special_tokens_list , show_progress=a_ , ) if isinstance(a_ , a_ ): UpperCAmelCase_ : str = [files] self._tokenizer.train(a_ , trainer=a_ ) self.add_unk_id() def a ( self : List[Any] , a_ : Union[Iterator[str], Iterator[Iterator[str]]] , a_ : int = 80_00 , a_ : bool = True , )-> Any: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = trainers.UnigramTrainer( vocab_size=a_ , special_tokens=self.special_tokens_list , show_progress=a_ , ) self._tokenizer.train_from_iterator(a_ , trainer=a_ ) self.add_unk_id() def a ( self : Dict )-> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = json.loads(self._tokenizer.to_str() ) UpperCAmelCase_ : Any = self.special_tokens["""unk"""]["""id"""] UpperCAmelCase_ : Tuple = Tokenizer.from_str(json.dumps(a_ ) )
470
1
import unittest from knapsack import greedy_knapsack as kp class __lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def _a ( self : str ): """simple docstring""" A__ = [10, 20, 30, 40, 50, 60] A__ = [2, 4, 6, 8, 10, 12] A__ = 1_00 self.assertEqual(kp.calc_profit(_snake_case , _snake_case , _snake_case ) , 2_10 ) def _a ( self : Any ): """simple docstring""" self.assertRaisesRegex(_snake_case , 'max_weight must greater than zero.' ) def _a ( self : str ): """simple docstring""" self.assertRaisesRegex(_snake_case , 'Weight can not be negative.' ) def _a ( self : Optional[Any] ): """simple docstring""" self.assertRaisesRegex(_snake_case , 'Profit can not be negative.' ) def _a ( self : Dict ): """simple docstring""" self.assertRaisesRegex(_snake_case , 'max_weight must greater than zero.' ) def _a ( self : List[str] ): """simple docstring""" self.assertRaisesRegex( _snake_case , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
52
import math import random def A ( __UpperCamelCase , __UpperCamelCase = False ) -> float: if deriv: return value * (1 - value) return 1 / (1 + math.exp(-value )) # Initial Value SCREAMING_SNAKE_CASE__ = 0.02 def A ( __UpperCamelCase , __UpperCamelCase ) -> float: A__ = float(2 * (random.randint(1 , 100 )) - 1 ) for _ in range(__UpperCamelCase ): # Forward propagation A__ = sigmoid_function(INITIAL_VALUE * weight ) # How much did we miss? A__ = (expected / 100) - layer_a # Error delta A__ = layer_1_error * sigmoid_function(__UpperCamelCase , __UpperCamelCase ) # Update weight weight += INITIAL_VALUE * layer_1_delta return layer_a * 100 if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE__ = int(input('''Expected value: ''')) SCREAMING_SNAKE_CASE__ = int(input('''Number of propagations: ''')) print(forward_propagation(expected, number_propagations))
52
1
'''simple docstring''' import argparse import torch from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt if __name__ == "__main__": UpperCAmelCase = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) # !wget https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml parser.add_argument( '--original_config_file', default=None, type=str, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--scheduler_type', default='pndm', type=str, help='Type of scheduler to use. Should be one of [\'pndm\', \'lms\', \'ddim\', \'euler\', \'euler-ancestral\', \'dpm\']', ) parser.add_argument( '--pipeline_type', default=None, type=str, help=( 'The pipeline type. One of \'FrozenOpenCLIPEmbedder\', \'FrozenCLIPEmbedder\', \'PaintByExample\'' '. If `None` pipeline will be automatically inferred.' ), ) parser.add_argument( '--image_size', default=None, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--prediction_type', default=None, type=str, help=( 'The prediction type that the model was trained on. Use \'epsilon\' for Stable Diffusion v1.X and Stable' ' Diffusion v2 Base. Use \'v_prediction\' for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') parser.add_argument( '--stable_unclip', type=str, default=None, required=False, help='Set if this is a stable unCLIP model. One of \'txt2img\' or \'img2img\'.', ) parser.add_argument( '--stable_unclip_prior', type=str, default=None, required=False, help='Set if this is a stable unCLIP txt2img model. Selects which prior to use. If `--stable_unclip` is set to `txt2img`, the karlo prior (https://huggingface.co/kakaobrain/karlo-v1-alpha/tree/main/prior) is selected by default.', ) parser.add_argument( '--clip_stats_path', type=str, help='Path to the clip stats file. Only required if the stable unclip model\'s config specifies `model.params.noise_aug_config.params.clip_stats_path`.', required=False, ) parser.add_argument( '--controlnet', action='store_true', default=None, help='Set flag if this is a controlnet checkpoint.' ) parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--vae_path', type=str, default=None, required=False, help='Set to a path, hub id to an already converted vae to not convert it again.', ) UpperCAmelCase = parser.parse_args() UpperCAmelCase = download_from_original_stable_diffusion_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, prediction_type=args.prediction_type, model_type=args.pipeline_type, extract_ema=args.extract_ema, scheduler_type=args.scheduler_type, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, stable_unclip=args.stable_unclip, stable_unclip_prior=args.stable_unclip_prior, clip_stats_path=args.clip_stats_path, controlnet=args.controlnet, vae_path=args.vae_path, ) if args.half: pipe.to(torch_dtype=torch.floataa) if args.controlnet: # only save the controlnet model pipe.controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors) else: pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
433
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { 'microsoft/git-base': 'https://huggingface.co/microsoft/git-base/resolve/main/config.json', } class __snake_case( _lowerCAmelCase ): '''simple docstring''' UpperCAmelCase : int = "git_vision_model" def __init__( self , A_=768 , A_=3072 , A_=12 , A_=12 , A_=3 , A_=224 , A_=16 , A_="quick_gelu" , A_=1e-5 , A_=0.0 , A_=0.0_2 , **A_ , ) -> Dict: super().__init__(**A_ ) lowerCAmelCase = hidden_size lowerCAmelCase = intermediate_size lowerCAmelCase = num_hidden_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = num_channels lowerCAmelCase = patch_size lowerCAmelCase = image_size lowerCAmelCase = initializer_range lowerCAmelCase = attention_dropout lowerCAmelCase = layer_norm_eps lowerCAmelCase = hidden_act @classmethod def __snake_case ( cls , A_ , **A_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(A_ ) lowerCAmelCase, lowerCAmelCase = cls.get_config_dict(A_ , **A_ ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": 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 __snake_case( _lowerCAmelCase ): '''simple docstring''' UpperCAmelCase : str = "git" def __init__( self , A_=None , A_=3_0522 , A_=768 , A_=6 , A_=12 , A_=3072 , A_="gelu" , A_=0.1 , A_=0.1 , A_=1024 , A_=0.0_2 , A_=1e-12 , A_=0 , A_="absolute" , A_=True , A_=False , A_=101 , A_=102 , A_=None , **A_ , ) -> Tuple: super().__init__(bos_token_id=A_ , eos_token_id=A_ , pad_token_id=A_ , **A_ ) if vision_config is None: lowerCAmelCase = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) lowerCAmelCase = GitVisionConfig(**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 = use_cache lowerCAmelCase = tie_word_embeddings lowerCAmelCase = num_image_with_embedding lowerCAmelCase = bos_token_id lowerCAmelCase = eos_token_id def __snake_case ( self ) -> List[Any]: lowerCAmelCase = copy.deepcopy(self.__dict__ ) lowerCAmelCase = self.vision_config.to_dict() lowerCAmelCase = self.__class__.model_type return output
433
1
'''simple docstring''' import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCAmelCase : Dict = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCAmelCase : List[str] = direct_transformers_import(PATH_TO_TRANSFORMERS) lowerCAmelCase : Optional[int] = transformers.models.auto.configuration_auto.CONFIG_MAPPING lowerCAmelCase : List[Any] = { # used to compute the property `self.chunk_length` '''EncodecConfig''': ['''overlap'''], # used as `self.bert_model = BertModel(config, ...)` '''DPRConfig''': True, # not used in modeling files, but it's an important information '''FSMTConfig''': ['''langs'''], # used internally in the configuration class file '''GPTNeoConfig''': ['''attention_types'''], # used internally in the configuration class file '''EsmConfig''': ['''is_folding_model'''], # used during training (despite we don't have training script for these models yet) '''Mask2FormerConfig''': ['''ignore_value'''], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) '''OneFormerConfig''': ['''ignore_value''', '''norm'''], # used during preprocessing and collation, see `collating_graphormer.py` '''GraphormerConfig''': ['''spatial_pos_max'''], # used internally in the configuration class file '''T5Config''': ['''feed_forward_proj'''], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally '''MT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''], '''UMT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''], # used internally in the configuration class file '''LongT5Config''': ['''feed_forward_proj'''], # used internally in the configuration class file '''SwitchTransformersConfig''': ['''feed_forward_proj'''], # having default values other than `1e-5` - we can't fix them without breaking '''BioGptConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''GLPNConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''SegformerConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''CvtConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''PerceiverConfig''': ['''layer_norm_eps'''], # used internally to calculate the feature size '''InformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate the feature size '''TimeSeriesTransformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate the feature size '''AutoformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate `mlp_dim` '''SamVisionConfig''': ['''mlp_ratio'''], # For (head) training, but so far not implemented '''ClapAudioConfig''': ['''num_classes'''], # Not used, but providing useful information to users '''SpeechT5HifiGanConfig''': ['''sampling_rate'''], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { '''CLIPSegConfig''': True, '''DeformableDetrConfig''': True, '''DetaConfig''': True, '''DinatConfig''': True, '''DonutSwinConfig''': True, '''EfficientFormerConfig''': True, '''FSMTConfig''': True, '''JukeboxConfig''': True, '''LayoutLMv2Config''': True, '''MaskFormerSwinConfig''': True, '''MT5Config''': True, '''NatConfig''': True, '''OneFormerConfig''': True, '''PerceiverConfig''': True, '''RagConfig''': True, '''SpeechT5Config''': True, '''SwinConfig''': True, '''Swin2SRConfig''': True, '''Swinv2Config''': True, '''SwitchTransformersConfig''': True, '''TableTransformerConfig''': True, '''TapasConfig''': True, '''TransfoXLConfig''': True, '''UniSpeechConfig''': True, '''UniSpeechSatConfig''': True, '''WavLMConfig''': True, '''WhisperConfig''': True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) '''JukeboxPriorConfig''': True, # TODO: @Younes (for `is_decoder`) '''Pix2StructTextConfig''': True, } ) def __lowerCAmelCase ( lowerCamelCase : int , lowerCamelCase : Dict , lowerCamelCase : Union[str, Any] , lowerCamelCase : str ): '''simple docstring''' __lowerCAmelCase = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( f'''config.{attribute}''' in modeling_source or f'''getattr(config, "{attribute}"''' in modeling_source or f'''getattr(self.config, "{attribute}"''' in modeling_source ): __lowerCAmelCase = True # Deal with multi-line cases elif ( re.search( rf'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"''' , lowerCamelCase , ) is not None ): __lowerCAmelCase = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: __lowerCAmelCase = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files __lowerCAmelCase = [ "bos_index", "eos_index", "pad_index", "unk_index", "mask_index", "image_size", "use_cache", "out_features", "out_indices", ] __lowerCAmelCase = ["encoder_no_repeat_ngram_size"] # Special cases to be allowed __lowerCAmelCase = True if not attribute_used: __lowerCAmelCase = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: __lowerCAmelCase = True elif attribute in ["tie_word_embeddings"] and default_value is False: __lowerCAmelCase = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: __lowerCAmelCase = True elif attribute.endswith("_token_id" ): __lowerCAmelCase = True # configuration class specific cases if not case_allowed: __lowerCAmelCase = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) __lowerCAmelCase = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def __lowerCAmelCase ( lowerCamelCase : int ): '''simple docstring''' __lowerCAmelCase = dict(inspect.signature(config_class.__init__ ).parameters ) __lowerCAmelCase = [x for x in list(signature.keys() ) if x not in ["self", "kwargs"]] __lowerCAmelCase = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass __lowerCAmelCase = {} if len(config_class.attribute_map ) > 0: __lowerCAmelCase = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files __lowerCAmelCase = inspect.getsourcefile(lowerCamelCase ) __lowerCAmelCase = os.path.dirname(lowerCamelCase ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. __lowerCAmelCase = [os.path.join(lowerCamelCase , lowerCamelCase ) for fn in os.listdir(lowerCamelCase ) if fn.startswith("modeling_" )] # Get the source code strings __lowerCAmelCase = [] for path in modeling_paths: if os.path.isfile(lowerCamelCase ): with open(lowerCamelCase ) as fp: modeling_sources.append(fp.read() ) __lowerCAmelCase = [] for config_param, default_value in zip(lowerCamelCase , lowerCamelCase ): # `attributes` here is all the variant names for `config_param` __lowerCAmelCase = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): unused_attributes.append(attributes[0] ) return sorted(lowerCamelCase ) def __lowerCAmelCase ( ): '''simple docstring''' __lowerCAmelCase = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) __lowerCAmelCase = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda lowerCamelCase : inspect.isclass(lowerCamelCase ) and issubclass(lowerCamelCase , lowerCamelCase ) and inspect.getmodule(lowerCamelCase ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: __lowerCAmelCase = check_config_attributes_being_used(lowerCamelCase ) if len(lowerCamelCase ) > 0: __lowerCAmelCase = unused_attributes if len(lowerCamelCase ) > 0: __lowerCAmelCase = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" for name, attributes in configs_with_unused_attributes.items(): error += f'''{name}: {attributes}\n''' raise ValueError(lowerCamelCase ) if __name__ == "__main__": check_config_attributes()
39
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase : Optional[Any] = logging.get_logger(__name__) lowerCAmelCase : Optional[int] = { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json''' ), } class UpperCAmelCase__ ( UpperCamelCase__ ): a : Optional[Any] = """dpr""" def __init__( self , UpperCamelCase=3_0522 , UpperCamelCase=768 , UpperCamelCase=12 , UpperCamelCase=12 , UpperCamelCase=3072 , UpperCamelCase="gelu" , UpperCamelCase=0.1 , UpperCamelCase=0.1 , UpperCamelCase=512 , UpperCamelCase=2 , UpperCamelCase=0.02 , UpperCamelCase=1E-12 , UpperCamelCase=0 , UpperCamelCase="absolute" , UpperCamelCase = 0 , **UpperCamelCase , ) -> Tuple: super().__init__(pad_token_id=UpperCamelCase , **UpperCamelCase ) __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 = type_vocab_size __lowerCAmelCase = initializer_range __lowerCAmelCase = layer_norm_eps __lowerCAmelCase = projection_dim __lowerCAmelCase = position_embedding_type
39
1
import argparse import json from typing import List from ltp import LTP from transformers.models.bert.tokenization_bert import BertTokenizer def _snake_case ( lowerCAmelCase : Union[str, Any] ): """simple docstring""" if ( (cp >= 0X4_E_0_0 and cp <= 0X9_F_F_F) or (cp >= 0X3_4_0_0 and cp <= 0X4_D_B_F) # or (cp >= 0X2_0_0_0_0 and cp <= 0X2_A_6_D_F) # or (cp >= 0X2_A_7_0_0 and cp <= 0X2_B_7_3_F) # or (cp >= 0X2_B_7_4_0 and cp <= 0X2_B_8_1_F) # or (cp >= 0X2_B_8_2_0 and cp <= 0X2_C_E_A_F) # or (cp >= 0XF_9_0_0 and cp <= 0XF_A_F_F) or (cp >= 0X2_F_8_0_0 and cp <= 0X2_F_A_1_F) # ): # return True return False def _snake_case ( lowerCAmelCase : str ): """simple docstring""" for char in word: SCREAMING_SNAKE_CASE_ : str = ord(lowerCAmelCase ) if not _is_chinese_char(lowerCAmelCase ): return 0 return 1 def _snake_case ( lowerCAmelCase : List[str] ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = set() for token in tokens: SCREAMING_SNAKE_CASE_ : Optional[Any] = len(lowerCAmelCase ) > 1 and is_chinese(lowerCAmelCase ) if chinese_word: word_set.add(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Any = list(lowerCAmelCase ) return word_list def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : set() ): """simple docstring""" if not chinese_word_set: return bert_tokens SCREAMING_SNAKE_CASE_ : Union[str, Any] = max([len(lowerCAmelCase ) for w in chinese_word_set] ) SCREAMING_SNAKE_CASE_ : List[str] = bert_tokens SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = 0, len(lowerCAmelCase ) while start < end: SCREAMING_SNAKE_CASE_ : Any = True if is_chinese(bert_word[start] ): SCREAMING_SNAKE_CASE_ : str = min(end - start , lowerCAmelCase ) for i in range(lowerCAmelCase , 1 , -1 ): SCREAMING_SNAKE_CASE_ : Optional[Any] = "".join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): SCREAMING_SNAKE_CASE_ : Dict = "##" + bert_word[j] SCREAMING_SNAKE_CASE_ : Optional[Any] = start + i SCREAMING_SNAKE_CASE_ : Optional[int] = False break if single_word: start += 1 return bert_word def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : LTP , lowerCAmelCase : BertTokenizer ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : str = ltp_tokenizer.pipeline(lines[i : i + 1_0_0] , tasks=["cws"] ).cws SCREAMING_SNAKE_CASE_ : Optional[int] = [get_chinese_word(lowerCAmelCase ) for r in res] ltp_res.extend(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Tuple = [] for i in range(0 , len(lowerCAmelCase ) , 1_0_0 ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=lowerCAmelCase , truncation=lowerCAmelCase , max_length=5_1_2 ) bert_res.extend(res["input_ids"] ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : int = [] for input_ids, chinese_word in zip(lowerCAmelCase , lowerCAmelCase ): SCREAMING_SNAKE_CASE_ : Optional[int] = [] for id in input_ids: SCREAMING_SNAKE_CASE_ : List[Any] = bert_tokenizer._convert_id_to_token(lowerCAmelCase ) input_tokens.append(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : List[Any] = add_sub_symbol(lowerCAmelCase , lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : str = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(lowerCAmelCase ): if token[:2] == "##": SCREAMING_SNAKE_CASE_ : str = token[2:] # save chinese tokens' pos if len(lowerCAmelCase ) == 1 and _is_chinese_char(ord(lowerCAmelCase ) ): ref_id.append(lowerCAmelCase ) ref_ids.append(lowerCAmelCase ) assert len(lowerCAmelCase ) == len(lowerCAmelCase ) return ref_ids def _snake_case ( lowerCAmelCase : str ): """simple docstring""" with open(args.file_name , "r" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : str = f.readlines() SCREAMING_SNAKE_CASE_ : Optional[Any] = [line.strip() for line in data if len(lowerCAmelCase ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' SCREAMING_SNAKE_CASE_ : Dict = LTP(args.ltp ) # faster in GPU device SCREAMING_SNAKE_CASE_ : int = BertTokenizer.from_pretrained(args.bert ) SCREAMING_SNAKE_CASE_ : int = prepare_ref(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) with open(args.save_path , "w" , encoding="utf-8" ) as f: SCREAMING_SNAKE_CASE_ : Optional[int] = [json.dumps(lowerCAmelCase ) + "\n" for ref in ref_ids] f.writelines(lowerCAmelCase ) if __name__ == "__main__": __lowerCamelCase : List[str] = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', required=False, type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', required=False, type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''', ) parser.add_argument( '''--bert''', required=False, type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''', ) parser.add_argument( '''--save_path''', required=False, type=str, default='''./resources/ref.txt''', help='''path to save res''', ) __lowerCamelCase : List[Any] = parser.parse_args() main(args)
216
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __lowerCamelCase : Dict = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class a__ ( datasets.BuilderConfig ): A = None def _snake_case ( lowerCAmelCase : "pyspark.sql.DataFrame" , lowerCAmelCase : List[int] , ): """simple docstring""" import pyspark def generate_fn(): SCREAMING_SNAKE_CASE_ : Optional[Any] = df.select("*" , pyspark.sql.functions.spark_partition_id().alias("part_id" ) ) for partition_id in partition_order: SCREAMING_SNAKE_CASE_ : Optional[Any] = df_with_partition_id.select("*" ).where(f'part_id = {partition_id}' ).drop("part_id" ) SCREAMING_SNAKE_CASE_ : List[str] = partition_df.collect() SCREAMING_SNAKE_CASE_ : Tuple = 0 for row in rows: yield f'{partition_id}_{row_id}', row.asDict() row_id += 1 return generate_fn class a__ ( _BaseExamplesIterable ): def __init__( self : Union[str, Any],_A : "pyspark.sql.DataFrame",_A : Any=None,): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = df SCREAMING_SNAKE_CASE_ : Tuple = partition_order or range(self.df.rdd.getNumPartitions() ) SCREAMING_SNAKE_CASE_ : Optional[Any] = _generate_iterable_examples(self.df,self.partition_order ) def __iter__( self : Union[str, Any] ): """simple docstring""" yield from self.generate_examples_fn() def __UpperCamelCase ( self : int,_A : np.random.Generator ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(_A ) return SparkExamplesIterable(self.df,partition_order=_A ) def __UpperCamelCase ( self : str,_A : int,_A : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.split_shard_indices_by_worker(_A,_A ) return SparkExamplesIterable(self.df,partition_order=_A ) @property def __UpperCamelCase ( self : str ): """simple docstring""" return len(self.partition_order ) class a__ ( datasets.DatasetBuilder ): A = SparkConfig def __init__( self : List[str],_A : "pyspark.sql.DataFrame",_A : str = None,_A : str = None,**_A : Optional[Any],): """simple docstring""" import pyspark SCREAMING_SNAKE_CASE_ : Union[str, Any] = pyspark.sql.SparkSession.builder.getOrCreate() SCREAMING_SNAKE_CASE_ : Optional[int] = df SCREAMING_SNAKE_CASE_ : Dict = working_dir super().__init__( cache_dir=_A,config_name=str(self.df.semanticHash() ),**_A,) def __UpperCamelCase ( self : int ): """simple docstring""" def create_cache_and_write_probe(_A : int ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir,exist_ok=_A ) SCREAMING_SNAKE_CASE_ : int = os.path.join(self._cache_dir,"fs_test" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(_A,"a" ) return [probe_file] if self._spark.conf.get("spark.master","" ).startswith("local" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: SCREAMING_SNAKE_CASE_ : Optional[Any] = ( self._spark.sparkContext.parallelize(range(1 ),1 ).mapPartitions(_A ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( "When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir" ) def __UpperCamelCase ( self : List[str] ): """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __UpperCamelCase ( self : Tuple,_A : datasets.download.download_manager.DownloadManager ): """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __UpperCamelCase ( self : Union[str, Any],_A : List[Any] ): """simple docstring""" import pyspark def get_arrow_batch_size(_A : Optional[Any] ): for batch in it: yield pa.RecordBatch.from_pydict({"batch_bytes": [batch.nbytes]} ) SCREAMING_SNAKE_CASE_ : Optional[int] = self.df.count() SCREAMING_SNAKE_CASE_ : str = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. SCREAMING_SNAKE_CASE_ : List[str] = ( self.df.limit(_A ) .repartition(1 ) .mapInArrow(_A,"batch_bytes: long" ) .agg(pyspark.sql.functions.sum("batch_bytes" ).alias("sample_bytes" ) ) .collect()[0] .sample_bytes / sample_num_rows ) SCREAMING_SNAKE_CASE_ : str = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. SCREAMING_SNAKE_CASE_ : int = min(_A,int(approx_total_size / max_shard_size ) ) SCREAMING_SNAKE_CASE_ : List[Any] = self.df.repartition(_A ) def __UpperCamelCase ( self : Any,_A : str,_A : str,_A : int,): """simple docstring""" import pyspark SCREAMING_SNAKE_CASE_ : Union[str, Any] = ParquetWriter if file_format == "parquet" else ArrowWriter SCREAMING_SNAKE_CASE_ : Tuple = os.path.join(self._working_dir,os.path.basename(_A ) ) if self._working_dir else fpath SCREAMING_SNAKE_CASE_ : Tuple = file_format == "parquet" # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. SCREAMING_SNAKE_CASE_ : Dict = self.config.features SCREAMING_SNAKE_CASE_ : Optional[int] = self._writer_batch_size SCREAMING_SNAKE_CASE_ : Tuple = self._fs.storage_options def write_arrow(_A : Optional[int] ): # Within the same SparkContext, no two task attempts will share the same attempt ID. SCREAMING_SNAKE_CASE_ : Any = pyspark.TaskContext().taskAttemptId() SCREAMING_SNAKE_CASE_ : List[Any] = next(_A,_A ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]],names=["task_id", "num_examples", "num_bytes"],) SCREAMING_SNAKE_CASE_ : Optional[int] = 0 SCREAMING_SNAKE_CASE_ : Tuple = writer_class( features=_A,path=working_fpath.replace("SSSSS",F'{shard_id:05d}' ).replace("TTTTT",F'{task_id:05d}' ),writer_batch_size=_A,storage_options=_A,embed_local_files=_A,) SCREAMING_SNAKE_CASE_ : Dict = pa.Table.from_batches([first_batch] ) writer.write_table(_A ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Union[str, Any] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]],names=["task_id", "num_examples", "num_bytes"],) shard_id += 1 SCREAMING_SNAKE_CASE_ : List[str] = writer_class( features=writer._features,path=working_fpath.replace("SSSSS",F'{shard_id:05d}' ).replace("TTTTT",F'{task_id:05d}' ),writer_batch_size=_A,storage_options=_A,embed_local_files=_A,) SCREAMING_SNAKE_CASE_ : List[Any] = pa.Table.from_batches([batch] ) writer.write_table(_A ) if writer._num_bytes > 0: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]],names=["task_id", "num_examples", "num_bytes"],) if working_fpath != fpath: for file in os.listdir(os.path.dirname(_A ) ): SCREAMING_SNAKE_CASE_ : List[str] = os.path.join(os.path.dirname(_A ),os.path.basename(_A ) ) shutil.move(_A,_A ) SCREAMING_SNAKE_CASE_ : Any = ( self.df.mapInArrow(_A,"task_id: long, num_examples: long, num_bytes: long" ) .groupBy("task_id" ) .agg( pyspark.sql.functions.sum("num_examples" ).alias("total_num_examples" ),pyspark.sql.functions.sum("num_bytes" ).alias("total_num_bytes" ),pyspark.sql.functions.count("num_bytes" ).alias("num_shards" ),pyspark.sql.functions.collect_list("num_examples" ).alias("shard_lengths" ),) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __UpperCamelCase ( self : Optional[int],_A : "datasets.SplitGenerator",_A : str = "arrow",_A : Optional[Union[str, int]] = None,_A : Optional[int] = None,**_A : Union[str, Any],): """simple docstring""" self._validate_cache_dir() SCREAMING_SNAKE_CASE_ : int = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(_A ) SCREAMING_SNAKE_CASE_ : List[Any] = not is_remote_filesystem(self._fs ) SCREAMING_SNAKE_CASE_ : int = os.path.join if is_local else posixpath.join SCREAMING_SNAKE_CASE_ : str = "-TTTTT-SSSSS-of-NNNNN" SCREAMING_SNAKE_CASE_ : Any = F'{self.name}-{split_generator.name}{SUFFIX}.{file_format}' SCREAMING_SNAKE_CASE_ : Dict = path_join(self._output_dir,_A ) SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = 0 SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : Any = [] for task_id, content in self._prepare_split_single(_A,_A,_A ): ( ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ( SCREAMING_SNAKE_CASE_ ) , ) : Union[str, Any] = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(_A ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = total_num_examples SCREAMING_SNAKE_CASE_ : Optional[int] = total_num_bytes # should rename everything at the end logger.debug(F'Renaming {total_shards} shards.' ) if total_shards > 1: SCREAMING_SNAKE_CASE_ : int = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. SCREAMING_SNAKE_CASE_ : List[Any] = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( _A : int,_A : int,_A : int,): rename( _A,fpath.replace("SSSSS",F'{shard_id:05d}' ).replace("TTTTT",F'{task_id:05d}' ),fpath.replace("TTTTT-SSSSS",F'{global_shard_id:05d}' ).replace("NNNNN",F'{total_shards:05d}' ),) SCREAMING_SNAKE_CASE_ : List[Any] = [] SCREAMING_SNAKE_CASE_ : List[str] = 0 for i in range(len(_A ) ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = task_id_and_num_shards[i] for shard_id in range(_A ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(_A,len(_A ) ).map(lambda _A : _rename_shard(*_A ) ).collect() else: # don't use any pattern SCREAMING_SNAKE_CASE_ : Any = 0 SCREAMING_SNAKE_CASE_ : Optional[int] = task_id_and_num_shards[0][0] self._rename( fpath.replace("SSSSS",F'{shard_id:05d}' ).replace("TTTTT",F'{task_id:05d}' ),fpath.replace(_A,"" ),) def __UpperCamelCase ( self : List[str],_A : "datasets.SplitGenerator",): """simple docstring""" return SparkExamplesIterable(self.df )
216
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Dict = { "configuration_deberta": ["DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP", "DebertaConfig", "DebertaOnnxConfig"], "tokenization_deberta": ["DebertaTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = ["DebertaTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDebertaForMaskedLM", "TFDebertaForQuestionAnswering", "TFDebertaForSequenceClassification", "TFDebertaForTokenClassification", "TFDebertaModel", "TFDebertaPreTrainedModel", ] if TYPE_CHECKING: from .configuration_deberta import DEBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, DebertaConfig, DebertaOnnxConfig from .tokenization_deberta import DebertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_deberta_fast import DebertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_deberta import ( DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, DebertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_deberta import ( TF_DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFDebertaForMaskedLM, TFDebertaForQuestionAnswering, TFDebertaForSequenceClassification, TFDebertaForTokenClassification, TFDebertaModel, TFDebertaPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
509
"""simple docstring""" from graphs.minimum_spanning_tree_kruskal import kruskal def A_ ( ) -> List[str]: a : List[Any] = 9 a : List[Any] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] a : int = kruskal(UpperCAmelCase__ , UpperCAmelCase__ ) a : List[Any] = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(UpperCAmelCase__ ) == sorted(UpperCAmelCase__ )
509
1
from __future__ import annotations class A_ : '''simple docstring''' def __init__( self , snake_case ): lowercase = order # a_{0} ... a_{k} lowercase = [1.0] + [0.0] * order # b_{0} ... b_{k} lowercase = [1.0] + [0.0] * order # x[n-1] ... x[n-k] lowercase = [0.0] * self.order # y[n-1] ... y[n-k] lowercase = [0.0] * self.order def SCREAMING_SNAKE_CASE__ ( self , snake_case , snake_case ): if len(snake_case ) < self.order: lowercase = [1.0, *a_coeffs] if len(snake_case ) != self.order + 1: lowercase = ( F'''Expected a_coeffs to have {self.order + 1} elements ''' F'''for {self.order}-order filter, got {len(snake_case )}''' ) raise ValueError(snake_case ) if len(snake_case ) != self.order + 1: lowercase = ( F'''Expected b_coeffs to have {self.order + 1} elements ''' F'''for {self.order}-order filter, got {len(snake_case )}''' ) raise ValueError(snake_case ) lowercase = a_coeffs lowercase = b_coeffs def SCREAMING_SNAKE_CASE__ ( self , snake_case ): lowercase = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) lowercase = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] lowercase = self.input_history[:-1] lowercase = self.output_history[:-1] lowercase = sample lowercase = result return result
84
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
440
0
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__ = { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/config.json""", """umberto-commoncrawl-cased-v1""": ( """https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json""" ), """umberto-wikipedia-uncased-v1""": ( """https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : Optional[Any] ='camembert' def __init__( self : Union[str, Any] , __lowercase : List[str]=30522 , __lowercase : List[str]=768 , __lowercase : Union[str, Any]=12 , __lowercase : List[str]=12 , __lowercase : str=3072 , __lowercase : Optional[int]="gelu" , __lowercase : List[Any]=0.1 , __lowercase : List[Any]=0.1 , __lowercase : List[str]=512 , __lowercase : Optional[Any]=2 , __lowercase : Tuple=0.02 , __lowercase : List[str]=1E-12 , __lowercase : int=1 , __lowercase : List[str]=0 , __lowercase : int=2 , __lowercase : str="absolute" , __lowercase : Optional[Any]=True , __lowercase : Any=None , **__lowercase : Tuple , ): '''simple docstring''' super().__init__(pad_token_id=__lowercase , bos_token_id=__lowercase , eos_token_id=__lowercase , **__lowercase ) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = position_embedding_type __a = use_cache __a = classifier_dropout class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): @property def UpperCamelCase_ ( self : str ): '''simple docstring''' if self.task == "multiple-choice": __a = {0: """batch""", 1: """choice""", 2: """sequence"""} else: __a = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
547
from dataclasses import dataclass from typing import Optional import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .modeling_utils import ModelMixin @dataclass class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): __lowerCamelCase : torch.FloatTensor class SCREAMING_SNAKE_CASE ( lowerCamelCase__ , lowerCamelCase__ ): @register_to_config def __init__( self : Tuple , __lowercase : int = 16 , __lowercase : int = 88 , __lowercase : Optional[int] = None , __lowercase : Optional[int] = None , __lowercase : int = 1 , __lowercase : float = 0.0 , __lowercase : int = 32 , __lowercase : Optional[int] = None , __lowercase : bool = False , __lowercase : Optional[int] = None , __lowercase : str = "geglu" , __lowercase : bool = True , __lowercase : bool = True , ): '''simple docstring''' super().__init__() __a = num_attention_heads __a = attention_head_dim __a = num_attention_heads * attention_head_dim __a = in_channels __a = torch.nn.GroupNorm(num_groups=__lowercase , num_channels=__lowercase , eps=1E-6 , affine=__lowercase ) __a = nn.Linear(__lowercase , __lowercase ) # 3. Define transformers blocks __a = nn.ModuleList( [ BasicTransformerBlock( __lowercase , __lowercase , __lowercase , dropout=__lowercase , cross_attention_dim=__lowercase , activation_fn=__lowercase , attention_bias=__lowercase , double_self_attention=__lowercase , norm_elementwise_affine=__lowercase , ) for d in range(__lowercase ) ] ) __a = nn.Linear(__lowercase , __lowercase ) def UpperCamelCase_ ( self : Any , __lowercase : Optional[Any] , __lowercase : str=None , __lowercase : List[Any]=None , __lowercase : List[Any]=None , __lowercase : int=1 , __lowercase : Union[str, Any]=None , __lowercase : bool = True , ): '''simple docstring''' __a , __a , __a , __a = hidden_states.shape __a = batch_frames // num_frames __a = hidden_states __a = hidden_states[None, :].reshape(__lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) __a = hidden_states.permute(0 , 2 , 1 , 3 , 4 ) __a = self.norm(__lowercase ) __a = hidden_states.permute(0 , 3 , 4 , 2 , 1 ).reshape(batch_size * height * width , __lowercase , __lowercase ) __a = self.proj_in(__lowercase ) # 2. Blocks for block in self.transformer_blocks: __a = block( __lowercase , encoder_hidden_states=__lowercase , timestep=__lowercase , cross_attention_kwargs=__lowercase , class_labels=__lowercase , ) # 3. Output __a = self.proj_out(__lowercase ) __a = ( hidden_states[None, None, :] .reshape(__lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) .permute(0 , 3 , 4 , 1 , 2 ) .contiguous() ) __a = hidden_states.reshape(__lowercase , __lowercase , __lowercase , __lowercase ) __a = hidden_states + residual if not return_dict: return (output,) return TransformerTemporalModelOutput(sample=__lowercase )
547
1
from __future__ import annotations def UpperCAmelCase_ ( __UpperCAmelCase : list[int] , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : int ) -> None: if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = array[indexa], array[indexa] def UpperCAmelCase_ ( __UpperCAmelCase : list[int] , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : int ) -> None: if length > 1: SCREAMING_SNAKE_CASE_ = int(length / 2 ) for i in range(__UpperCAmelCase , low + middle ): comp_and_swap(__UpperCAmelCase , __UpperCAmelCase , i + middle , __UpperCAmelCase ) bitonic_merge(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) bitonic_merge(__UpperCAmelCase , low + middle , __UpperCAmelCase , __UpperCAmelCase ) def UpperCAmelCase_ ( __UpperCAmelCase : list[int] , __UpperCAmelCase : int , __UpperCAmelCase : int , __UpperCAmelCase : int ) -> None: if length > 1: SCREAMING_SNAKE_CASE_ = int(length / 2 ) bitonic_sort(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , 1 ) bitonic_sort(__UpperCAmelCase , low + middle , __UpperCAmelCase , 0 ) bitonic_merge(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) if __name__ == "__main__": lowerCamelCase__ : Optional[Any] = input('Enter numbers separated by a comma:\n').strip() lowerCamelCase__ : Tuple = [int(item.strip()) for item in user_input.split(',')] bitonic_sort(unsorted, 0, len(unsorted), 1) print('\nSorted array in ascending order is: ', end='') print(*unsorted, sep=', ') bitonic_merge(unsorted, 0, len(unsorted), 0) print('Sorted array in descending order is: ', end='') print(*unsorted, sep=', ')
31
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowerCamelCase : Optional[Any] = False try: lowerCamelCase : Union[str, Any] = _is_package_available("google.colab") except ModuleNotFoundError: pass @input.register class A__ : def __init__( self : Tuple , _a : str = None , _a : list = [] ) -> str: '''simple docstring''' _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =choices _SCREAMING_SNAKE_CASE =prompt if sys.platform == "win32": _SCREAMING_SNAKE_CASE ='*' else: _SCREAMING_SNAKE_CASE ='➔ ' def A ( self : Dict , _a : Union[str, Any] , _a : str = "" ) -> Dict: '''simple docstring''' if sys.platform != "win32": writeColor(self.choices[index] , 32 , _a ) else: forceWrite(self.choices[index] , _a ) def A ( self : str , _a : int ) -> int: '''simple docstring''' if index == self.position: forceWrite(f" {self.arrow_char} " ) self.write_choice(_a ) else: forceWrite(f" {self.choices[index]}" ) reset_cursor() def A ( self : Tuple , _a : Direction , _a : int = 1 ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(_a ) move_cursor(_a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def A ( self : int ) -> Optional[Any]: '''simple docstring''' self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def A ( self : Any ) -> List[Any]: '''simple docstring''' self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def A ( self : Any ) -> List[Any]: '''simple docstring''' move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def A ( self : Union[str, Any] ) -> str: '''simple docstring''' move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(_a )] for number in range(10 )] ) def A ( self : Tuple ) -> List[Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =int(chr(self.current_selection ) ) _SCREAMING_SNAKE_CASE =index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , _a ) else: return else: return def A ( self : str , _a : int = 0 ) -> Optional[Any]: '''simple docstring''' if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) _SCREAMING_SNAKE_CASE =default_choice for i in range(len(self.choices ) ): self.print_choice(_a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: _SCREAMING_SNAKE_CASE =int(builtins.input() ) except ValueError: _SCREAMING_SNAKE_CASE =default_choice else: _SCREAMING_SNAKE_CASE =self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(_a , '\n' ) return choice
405
0
"""simple docstring""" def _snake_case ( UpperCAmelCase_ : str ): if divisor % 5 == 0 or divisor % 2 == 0: return 0 A__ = 1 A__ = 1 while repunit: A__ = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def _snake_case ( UpperCAmelCase_ : Dict = 100_0000 ): A__ = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(_A ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f"""{solution() = }""")
719
"""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() SCREAMING_SNAKE_CASE_ : Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ : Any = ['model.decoder.embed_positions.weights'] def _snake_case ( UpperCAmelCase_ : Optional[int] ): if "emb" in name: A__ = name.replace("""emb""" , """model.decoder.embed_tokens""" ) if "transformer" in name: A__ = name.replace("""transformer""" , """model.decoder""" ) if "cross_attention" in name: A__ = name.replace("""cross_attention""" , """encoder_attn""" ) if "linear1" in name: A__ = name.replace("""linear1""" , """fc1""" ) if "linear2" in name: A__ = name.replace("""linear2""" , """fc2""" ) if "norm1" in name: A__ = name.replace("""norm1""" , """self_attn_layer_norm""" ) if "norm_cross" in name: A__ = name.replace("""norm_cross""" , """encoder_attn_layer_norm""" ) if "norm2" in name: A__ = name.replace("""norm2""" , """final_layer_norm""" ) if "out_norm" in name: A__ = name.replace("""out_norm""" , """model.decoder.layer_norm""" ) if "linears" in name: A__ = name.replace("""linears""" , """lm_heads""" ) if "condition_provider.conditioners.description.output_proj" in name: A__ = name.replace("""condition_provider.conditioners.description.output_proj""" , """enc_to_dec_proj""" ) return name def _snake_case ( UpperCAmelCase_ : OrderedDict , UpperCAmelCase_ : int ): A__ = list(state_dict.keys() ) A__ = {} for key in keys: A__ = state_dict.pop(UpperCAmelCase_ ) A__ = rename_keys(UpperCAmelCase_ ) if "in_proj_weight" in key: # split fused qkv proj A__ = val[:hidden_size, :] A__ = val[hidden_size : 2 * hidden_size, :] A__ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: A__ = val else: A__ = val return state_dict, enc_dec_proj_state_dict def _snake_case ( UpperCAmelCase_ : str ): if checkpoint == "small": # default config values A__ = 1024 A__ = 24 A__ = 16 elif checkpoint == "medium": A__ = 1536 A__ = 48 A__ = 24 elif checkpoint == "large": A__ = 2048 A__ = 48 A__ = 32 else: raise ValueError(F"""Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}.""" ) A__ = MusicgenDecoderConfig( hidden_size=UpperCAmelCase_ , ffn_dim=hidden_size * 4 , num_hidden_layers=UpperCAmelCase_ , num_attention_heads=UpperCAmelCase_ , ) return config @torch.no_grad() def _snake_case ( UpperCAmelCase_ : int , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Any="cpu" ): A__ = MusicGen.get_pretrained(UpperCAmelCase_ , device=UpperCAmelCase_ ) A__ = decoder_config_from_checkpoint(UpperCAmelCase_ ) A__ = fairseq_model.lm.state_dict() A__ , A__ = rename_state_dict( UpperCAmelCase_ , hidden_size=decoder_config.hidden_size ) A__ = TaEncoderModel.from_pretrained("""t5-base""" ) A__ = EncodecModel.from_pretrained("""facebook/encodec_32khz""" ) A__ = MusicgenForCausalLM(UpperCAmelCase_ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection A__ , A__ = decoder.load_state_dict(UpperCAmelCase_ , strict=UpperCAmelCase_ ) for key in missing_keys.copy(): if key.startswith(("""text_encoder""", """audio_encoder""") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(UpperCAmelCase_ ) if len(UpperCAmelCase_ ) > 0: raise ValueError(F"""Missing key(s) in state_dict: {missing_keys}""" ) if len(UpperCAmelCase_ ) > 0: raise ValueError(F"""Unexpected key(s) in state_dict: {unexpected_keys}""" ) # init the composite model A__ = MusicgenForConditionalGeneration(text_encoder=UpperCAmelCase_ , audio_encoder=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(UpperCAmelCase_ ) # check we can do a forward pass A__ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) A__ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): A__ = model(input_ids=UpperCAmelCase_ , decoder_input_ids=UpperCAmelCase_ ).logits if logits.shape != (8, 1, 2048): raise ValueError("""Incorrect shape for logits""" ) # now construct the processor A__ = AutoTokenizer.from_pretrained("""t5-base""" ) A__ = AutoFeatureExtractor.from_pretrained("""facebook/encodec_32khz""" , padding_side="""left""" ) A__ = MusicgenProcessor(feature_extractor=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ ) # set the appropriate bos/pad token ids A__ = 2048 A__ = 2048 # set other default generation config params A__ = int(30 * audio_encoder.config.frame_rate ) A__ = True A__ = 3.0 if pytorch_dump_folder is not None: Path(UpperCAmelCase_ ).mkdir(exist_ok=UpperCAmelCase_ ) logger.info(F"""Saving model {checkpoint} to {pytorch_dump_folder}""" ) model.save_pretrained(UpperCAmelCase_ ) processor.save_pretrained(UpperCAmelCase_ ) if repo_id: logger.info(F"""Pushing model {checkpoint} to {repo_id}""" ) model.push_to_hub(UpperCAmelCase_ ) processor.push_to_hub(UpperCAmelCase_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ : int = 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.' ) SCREAMING_SNAKE_CASE_ : Tuple = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
500
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { "microsoft/focalnet-tiny": "https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json", } class lowerCAmelCase ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" _A = 'focalnet' def __init__( self , _A=224 , _A=4 , _A=3 , _A=96 , _A=False , _A=[192, 384, 768, 768] , _A=[2, 2, 6, 2] , _A=[2, 2, 2, 2] , _A=[3, 3, 3, 3] , _A="gelu" , _A=4.0 , _A=0.0 , _A=0.1 , _A=False , _A=1E-4 , _A=False , _A=False , _A=False , _A=0.02 , _A=1E-5 , _A=32 , _A=None , _A=None , **_A , ) -> List[str]: super().__init__(**_A ) __a : Tuple = image_size __a : str = patch_size __a : List[Any] = num_channels __a : Union[str, Any] = embed_dim __a : Dict = use_conv_embed __a : List[str] = hidden_sizes __a : Optional[int] = depths __a : List[str] = focal_levels __a : str = focal_windows __a : List[str] = hidden_act __a : int = mlp_ratio __a : Optional[int] = hidden_dropout_prob __a : Optional[Any] = drop_path_rate __a : Union[str, Any] = use_layerscale __a : Optional[int] = layerscale_value __a : List[Any] = use_post_layernorm __a : str = use_post_layernorm_in_modulation __a : str = normalize_modulator __a : int = initializer_range __a : int = layer_norm_eps __a : str = encoder_stride __a : Optional[int] = ['stem'] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] __a , __a : Any = get_aligned_output_features_output_indices( out_features=_A , out_indices=_A , stage_names=self.stage_names )
597
'''simple docstring''' import argparse import os from pathlib import Path import fairseq import torch from packaging import version from torch import nn from transformers import ( BartConfig, BartForConditionalGeneration, BartForSequenceClassification, BartModel, BartTokenizer, ) from transformers.utils import logging SCREAMING_SNAKE_CASE_ = ["bart.large", "bart.large.mnli", "bart.large.cnn", "bart_xsum/model.pt"] SCREAMING_SNAKE_CASE_ = {"bart.large": BartModel, "bart.large.mnli": BartForSequenceClassification} if version.parse(fairseq.__version__) < version.parse("0.9.0"): raise Exception("requires fairseq >= 0.9.0") logging.set_verbosity_info() SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = " Hello world! cécé herlolip" SCREAMING_SNAKE_CASE_ = [ ("model.classification_heads.mnli.dense.weight", "classification_head.dense.weight"), ("model.classification_heads.mnli.dense.bias", "classification_head.dense.bias"), ("model.classification_heads.mnli.out_proj.weight", "classification_head.out_proj.weight"), ("model.classification_heads.mnli.out_proj.bias", "classification_head.out_proj.bias"), ] def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ ): __a : Dict = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', ] for k in ignore_keys: state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __a : Dict = dct.pop(SCREAMING_SNAKE_CASE__ ) __a : Dict = val def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ ): __a : Dict = torch.load(SCREAMING_SNAKE_CASE__ , map_location='cpu' ) __a : Dict = torch.hub.load('pytorch/fairseq' , 'bart.large.cnn' ).eval() hub_interface.model.load_state_dict(sd['model'] ) return hub_interface def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ ): __a , __a : Dict = emb.weight.shape __a : Optional[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ ) __a : List[Any] = emb.weight.data return lin_layer @torch.no_grad() def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): if not os.path.exists(SCREAMING_SNAKE_CASE__ ): __a : Tuple = torch.hub.load('pytorch/fairseq' , SCREAMING_SNAKE_CASE__ ).eval() else: __a : Optional[int] = load_xsum_checkpoint(SCREAMING_SNAKE_CASE__ ) bart.model.upgrade_state_dict(bart.model.state_dict() ) if hf_checkpoint_name is None: __a : List[str] = checkpoint_path.replace('.' , '-' ) __a : Optional[Any] = BartConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) __a : Union[str, Any] = bart.encode(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) __a : List[str] = BartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ).encode(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).unsqueeze(0 ) if not torch.eq(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).all(): raise ValueError( f'''converted tokenizer and pretrained tokenizer returned different output: {tokens} != {tokensa}''' ) if checkpoint_path == "bart.large.mnli": __a : List[Any] = bart.state_dict() remove_ignore_keys_(SCREAMING_SNAKE_CASE__ ) __a : str = state_dict['model.decoder.embed_tokens.weight'] for src, dest in mnli_rename_keys: rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __a : Dict = BartForSequenceClassification(SCREAMING_SNAKE_CASE__ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) __a : Any = bart.predict('mnli' , SCREAMING_SNAKE_CASE__ , return_logits=SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = model(SCREAMING_SNAKE_CASE__ )[0] # logits else: # no classification heads to worry about __a : Dict = bart.model.state_dict() remove_ignore_keys_(SCREAMING_SNAKE_CASE__ ) __a : Optional[Any] = state_dict['decoder.embed_tokens.weight'] __a : List[Any] = bart.extract_features(SCREAMING_SNAKE_CASE__ ) if hf_checkpoint_name == "facebook/bart-large": __a : Dict = BartModel(SCREAMING_SNAKE_CASE__ ).eval() model.load_state_dict(SCREAMING_SNAKE_CASE__ ) __a : str = model(SCREAMING_SNAKE_CASE__ ).model[0] else: __a : Optional[Any] = BartForConditionalGeneration(SCREAMING_SNAKE_CASE__ ).eval() # an existing summarization ckpt model.model.load_state_dict(SCREAMING_SNAKE_CASE__ ) if hasattr(SCREAMING_SNAKE_CASE__ , 'lm_head' ): __a : Optional[int] = make_linear_from_emb(model.model.shared ) __a : List[Any] = model.model(SCREAMING_SNAKE_CASE__ )[0] # Check results if fairseq_output.shape != new_model_outputs.shape: raise ValueError( f'''`fairseq_output` shape and `new_model_output` shape are different: {fairseq_output.shape=}, {new_model_outputs.shape}''' ) if (fairseq_output != new_model_outputs).any().item(): raise ValueError('Some values in `fairseq_output` are different from `new_model_outputs`' ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser() # Required parameters parser.add_argument( "fairseq_path", type=str, help="bart.large, bart.large.cnn or a path to a model.pt on local filesystem." ) parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument( "--hf_config", default=None, type=str, help="Which huggingface architecture to use: bart-large-xsum" ) SCREAMING_SNAKE_CASE_ = parser.parse_args() convert_bart_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, hf_checkpoint_name=args.hf_config)
597
1
'''simple docstring''' 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 ( SCREAMING_SNAKE_CASE ): """simple docstring""" def __magic_name__ ( self : Optional[Any] ): '''simple docstring''' snake_case__ : str = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(snake_case_ , '''width_multiplier''' ) ) class a : """simple docstring""" def __init__( self : List[str] , snake_case_ : Optional[int] , snake_case_ : Dict=1_3 , snake_case_ : Any=6_4 , snake_case_ : Dict=2 , snake_case_ : Optional[int]=3 , snake_case_ : str="swish" , snake_case_ : str=3 , snake_case_ : Union[str, Any]=3_2 , snake_case_ : Optional[Any]=0.1 , snake_case_ : Any=0.0_2 , snake_case_ : int=True , snake_case_ : Tuple=True , snake_case_ : Dict=1_0 , snake_case_ : Optional[int]=None , snake_case_ : str=0.2_5 , snake_case_ : List[Any]=0.0 , snake_case_ : Optional[Any]=0.0 , ): '''simple docstring''' snake_case__ : List[Any] = parent snake_case__ : Dict = batch_size snake_case__ : Dict = image_size snake_case__ : Tuple = patch_size snake_case__ : Tuple = num_channels snake_case__ : Tuple = make_divisible(5_1_2 * width_multiplier , divisor=8 ) snake_case__ : Optional[int] = hidden_act snake_case__ : int = conv_kernel_size snake_case__ : Optional[int] = output_stride snake_case__ : List[Any] = classifier_dropout_prob snake_case__ : int = use_labels snake_case__ : Optional[Any] = is_training snake_case__ : int = num_labels snake_case__ : str = initializer_range snake_case__ : Dict = scope snake_case__ : Tuple = width_multiplier snake_case__ : Optional[Any] = ffn_dropout snake_case__ : Dict = attn_dropout def __magic_name__ ( self : str ): '''simple docstring''' snake_case__ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[str] = None snake_case__ : Union[str, Any] = None if self.use_labels: snake_case__ : Tuple = ids_tensor([self.batch_size] , self.num_labels ) snake_case__ : Optional[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) snake_case__ : Optional[int] = self.get_config() return config, pixel_values, labels, pixel_labels def __magic_name__ ( self : List[str] ): '''simple docstring''' 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 __magic_name__ ( self : Optional[Any] , snake_case_ : Optional[int] , snake_case_ : Optional[int] , snake_case_ : Optional[Any] , snake_case_ : Optional[Any] ): '''simple docstring''' snake_case__ : Optional[Any] = MobileViTVaModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() snake_case__ : Dict = model(snake_case_ ) 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 __magic_name__ ( self : Union[str, Any] , snake_case_ : Optional[int] , snake_case_ : List[Any] , snake_case_ : Tuple , snake_case_ : Optional[Any] ): '''simple docstring''' snake_case__ : Optional[int] = self.num_labels snake_case__ : Optional[Any] = MobileViTVaForImageClassification(snake_case_ ) model.to(snake_case_ ) model.eval() snake_case__ : int = model(snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __magic_name__ ( self : int , snake_case_ : List[Any] , snake_case_ : Dict , snake_case_ : Any , snake_case_ : List[str] ): '''simple docstring''' snake_case__ : Dict = self.num_labels snake_case__ : Any = MobileViTVaForSemanticSegmentation(snake_case_ ) model.to(snake_case_ ) model.eval() snake_case__ : str = model(snake_case_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) snake_case__ : Optional[int] = model(snake_case_ , labels=snake_case_ ) 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 __magic_name__ ( self : str ): '''simple docstring''' snake_case__ : Dict = self.prepare_config_and_inputs() snake_case__ : List[str] = config_and_inputs snake_case__ : List[str] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { """feature-extraction""": MobileViTVaModel, """image-classification""": MobileViTVaForImageClassification, """image-segmentation""": MobileViTVaForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def __magic_name__ ( self : int ): '''simple docstring''' snake_case__ : str = MobileViTVaModelTester(self ) snake_case__ : Union[str, Any] = MobileViTVaConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_ ) def __magic_name__ ( self : List[str] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' ) def __magic_name__ ( self : Optional[int] ): '''simple docstring''' pass @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' ) def __magic_name__ ( self : Optional[int] ): '''simple docstring''' pass @unittest.skip(reason='''MobileViTV2 does not output attentions''' ) def __magic_name__ ( self : int ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason='''Got `CUDA error: misaligned address` for tests after this one being run.''' ) def __magic_name__ ( self : int ): '''simple docstring''' pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def __magic_name__ ( self : Optional[Any] ): '''simple docstring''' pass def __magic_name__ ( self : Optional[Any] ): '''simple docstring''' snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Optional[int] = model_class(snake_case_ ) snake_case__ : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Any = [*signature.parameters.keys()] snake_case__ : Optional[int] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , snake_case_ ) def __magic_name__ ( self : List[str] ): '''simple docstring''' snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def __magic_name__ ( self : List[str] ): '''simple docstring''' def check_hidden_states_output(snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : Tuple ): snake_case__ : Optional[Any] = model_class(snake_case_ ) model.to(snake_case_ ) model.eval() with torch.no_grad(): snake_case__ : Tuple = model(**self._prepare_for_class(snake_case_ , snake_case_ ) ) snake_case__ : Union[str, Any] = outputs.hidden_states snake_case__ : Any = 5 self.assertEqual(len(snake_case_ ) , snake_case_ ) # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. snake_case__ : Dict = 2 for i in range(len(snake_case_ ) ): 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 ) 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[str] = True check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : int = True check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ ) def __magic_name__ ( self : int ): '''simple docstring''' snake_case__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case_ ) def __magic_name__ ( self : Any ): '''simple docstring''' snake_case__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case_ ) @slow def __magic_name__ ( self : List[Any] ): '''simple docstring''' for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : Any = MobileViTVaModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) def _a ( ): """simple docstring""" snake_case__ : Optional[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class a ( unittest.TestCase ): """simple docstring""" @cached_property def __magic_name__ ( self : Optional[int] ): '''simple docstring''' return ( MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ) if is_vision_available() else None ) @slow def __magic_name__ ( self : Tuple ): '''simple docstring''' snake_case__ : Tuple = MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to( snake_case_ ) snake_case__ : Any = self.default_image_processor snake_case__ : Tuple = prepare_img() snake_case__ : str = image_processor(images=snake_case_ , return_tensors='''pt''' ).to(snake_case_ ) # forward pass with torch.no_grad(): snake_case__ : Any = model(**snake_case_ ) # verify the logits snake_case__ : Dict = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , snake_case_ ) snake_case__ : Tuple = torch.tensor([-1.6_336e00, -7.3_204e-02, -5.1_883e-01] ).to(snake_case_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , snake_case_ , atol=1e-4 ) ) @slow def __magic_name__ ( self : Tuple ): '''simple docstring''' snake_case__ : List[Any] = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) snake_case__ : Any = model.to(snake_case_ ) snake_case__ : Tuple = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) snake_case__ : str = prepare_img() snake_case__ : Union[str, Any] = image_processor(images=snake_case_ , return_tensors='''pt''' ).to(snake_case_ ) # forward pass with torch.no_grad(): snake_case__ : Union[str, Any] = model(**snake_case_ ) snake_case__ : Tuple = outputs.logits # verify the logits snake_case__ : Optional[Any] = torch.Size((1, 2_1, 3_2, 3_2) ) self.assertEqual(logits.shape , snake_case_ ) snake_case__ : List[Any] = 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=snake_case_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , snake_case_ , atol=1e-4 ) ) @slow def __magic_name__ ( self : List[Any] ): '''simple docstring''' snake_case__ : Optional[int] = MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) snake_case__ : List[str] = model.to(snake_case_ ) snake_case__ : Optional[int] = MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' ) snake_case__ : str = prepare_img() snake_case__ : str = image_processor(images=snake_case_ , return_tensors='''pt''' ).to(snake_case_ ) # forward pass with torch.no_grad(): snake_case__ : Any = model(**snake_case_ ) snake_case__ : str = outputs.logits.detach().cpu() snake_case__ : int = image_processor.post_process_semantic_segmentation(outputs=snake_case_ , target_sizes=[(5_0, 6_0)] ) snake_case__ : int = torch.Size((5_0, 6_0) ) self.assertEqual(segmentation[0].shape , snake_case_ ) snake_case__ : str = image_processor.post_process_semantic_segmentation(outputs=snake_case_ ) snake_case__ : Any = torch.Size((3_2, 3_2) ) self.assertEqual(segmentation[0].shape , snake_case_ )
717
'''simple docstring''' from collections.abc import Sequence def _a ( __lowerCAmelCase : Sequence[int] | None = None ): """simple docstring""" if nums is None or not nums: raise ValueError('''Input sequence should not be empty''' ) snake_case__ : Optional[Any] = nums[0] for i in range(1 , len(__lowerCAmelCase ) ): snake_case__ : Tuple = nums[i] snake_case__ : Optional[int] = max(__lowerCAmelCase , ans + num , __lowerCAmelCase ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user lowerCAmelCase__ : str = int(input("""Enter number of elements : """).strip()) lowerCAmelCase__ : Dict = list(map(int, input("""\nEnter the numbers : """).strip().split()))[:n] print(max_subsequence_sum(array))
502
0
import sys lowerCamelCase : int = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def _SCREAMING_SNAKE_CASE ( lowercase : str = N ): '''simple docstring''' lowerCamelCase_ = -sys.maxsize - 1 for i in range(len(lowercase ) - 12 ): lowerCamelCase_ = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: lowerCamelCase_ = product return largest_product if __name__ == "__main__": print(F"""{solution() = }""")
70
import unittest import torch from diffusers import DDIMScheduler, DDPMScheduler, UNetaDModel from diffusers.training_utils import set_seed from diffusers.utils.testing_utils import slow lowerCamelCase : int = False class A( unittest.TestCase ): '''simple docstring''' def a__ ( self : int , A_ : Dict=32 ) -> Any: """simple docstring""" set_seed(0 ) lowerCamelCase_ = UNetaDModel(sample_size=A_ , in_channels=3 , out_channels=3 ) lowerCamelCase_ = torch.optim.SGD(model.parameters() , lr=0.0001 ) return model, optimizer @slow def a__ ( self : int ) -> str: """simple docstring""" lowerCamelCase_ = 'cpu' # ensure full determinism without setting the CUBLAS_WORKSPACE_CONFIG env variable lowerCamelCase_ = DDPMScheduler( num_train_timesteps=1000 , beta_start=0.0001 , beta_end=0.02 , beta_schedule='linear' , clip_sample=A_ , ) lowerCamelCase_ = DDIMScheduler( num_train_timesteps=1000 , beta_start=0.0001 , beta_end=0.02 , beta_schedule='linear' , clip_sample=A_ , ) assert ddpm_scheduler.config.num_train_timesteps == ddim_scheduler.config.num_train_timesteps # shared batches for DDPM and DDIM set_seed(0 ) lowerCamelCase_ = [torch.randn((4, 3, 32, 32) ).clip(-1 , 1 ).to(A_ ) for _ in range(4 )] lowerCamelCase_ = [torch.randn((4, 3, 32, 32) ).to(A_ ) for _ in range(4 )] lowerCamelCase_ = [torch.randint(0 , 1000 , (4,) ).long().to(A_ ) for _ in range(4 )] # train with a DDPM scheduler lowerCamelCase_ , lowerCamelCase_ = self.get_model_optimizer(resolution=32 ) model.train().to(A_ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase_ = ddpm_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase_ = model(A_ , timesteps[i] ).sample lowerCamelCase_ = torch.nn.functional.mse_loss(A_ , noise[i] ) loss.backward() optimizer.step() del model, optimizer # recreate the model and optimizer, and retry with DDIM lowerCamelCase_ , lowerCamelCase_ = self.get_model_optimizer(resolution=32 ) model.train().to(A_ ) for i in range(4 ): optimizer.zero_grad() lowerCamelCase_ = ddim_scheduler.add_noise(clean_images[i] , noise[i] , timesteps[i] ) lowerCamelCase_ = model(A_ , timesteps[i] ).sample lowerCamelCase_ = torch.nn.functional.mse_loss(A_ , noise[i] ) loss.backward() optimizer.step() del model, optimizer self.assertTrue(torch.allclose(A_ , A_ , atol=1E-5 ) ) self.assertTrue(torch.allclose(A_ , A_ , atol=1E-5 ) )
70
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : Any = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): for attribute in key.split(""".""" ): __magic_name__ : List[str] =getattr(lowerCamelCase , lowerCamelCase ) if weight_type is not None: __magic_name__ : Optional[int] =getattr(lowerCamelCase , lowerCamelCase ).shape else: __magic_name__ : Tuple =hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __magic_name__ : Any =value elif weight_type == "weight_g": __magic_name__ : Optional[Any] =value elif weight_type == "weight_v": __magic_name__ : int =value elif weight_type == "bias": __magic_name__ : int =value else: __magic_name__ : int =value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): __magic_name__ : Any =[] __magic_name__ : Optional[int] =fairseq_model.state_dict() __magic_name__ : Optional[Any] =hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): __magic_name__ : int =False if "conv_layers" in name: load_conv_layer( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , hf_model.config.feat_extract_norm == """group""" , ) __magic_name__ : Optional[int] =True else: for key, mapped_key in MAPPING.items(): __magic_name__ : List[str] ="""hubert.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or (key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0] and not is_finetuned): __magic_name__ : Optional[int] =True if "*" in mapped_key: __magic_name__ : Any =name.split(lowerCamelCase )[0].split(""".""" )[-2] __magic_name__ : Optional[int] =mapped_key.replace("""*""" , lowerCamelCase ) if "weight_g" in name: __magic_name__ : Optional[int] ="""weight_g""" elif "weight_v" in name: __magic_name__ : int ="""weight_v""" elif "weight" in name: __magic_name__ : Optional[Any] ="""weight""" elif "bias" in name: __magic_name__ : List[Any] ="""bias""" else: __magic_name__ : Union[str, Any] =None set_recursively(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) continue if not is_used: unused_weights.append(lowerCamelCase ) logger.warning(F"Unused weights: {unused_weights}" ) def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __magic_name__ : Any =full_name.split("""conv_layers.""" )[-1] __magic_name__ : Any =name.split(""".""" ) __magic_name__ : Any =int(items[0] ) __magic_name__ : Union[str, Any] =int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __magic_name__ : Any =value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __magic_name__ : Union[str, Any] =value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __magic_name__ : Optional[int] =value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __magic_name__ : Dict =value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(lowerCamelCase ) @torch.no_grad() def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=True ): if config_path is not None: __magic_name__ : List[Any] =HubertConfig.from_pretrained(lowerCamelCase ) else: __magic_name__ : int =HubertConfig() if is_finetuned: if dict_path: __magic_name__ : List[str] =Dictionary.load(lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __magic_name__ : Union[str, Any] =target_dict.pad_index __magic_name__ : int =target_dict.bos_index __magic_name__ : Dict =target_dict.eos_index __magic_name__ : str =len(target_dict.symbols ) __magic_name__ : List[Any] =os.path.join(lowerCamelCase , """vocab.json""" ) if not os.path.isdir(lowerCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(lowerCamelCase ) ) return os.makedirs(lowerCamelCase , exist_ok=lowerCamelCase ) with open(lowerCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , lowerCamelCase ) __magic_name__ : Any =WavaVecaCTCTokenizer( lowerCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=lowerCamelCase , ) __magic_name__ : List[Any] =True if config.feat_extract_norm == """layer""" else False __magic_name__ : Optional[Any] =WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowerCamelCase , return_attention_mask=lowerCamelCase , ) __magic_name__ : Optional[Any] =WavaVecaProcessor(feature_extractor=lowerCamelCase , tokenizer=lowerCamelCase ) processor.save_pretrained(lowerCamelCase ) __magic_name__ : Tuple =HubertForCTC(lowerCamelCase ) else: __magic_name__ : Union[str, Any] =HubertModel(lowerCamelCase ) if is_finetuned: __magic_name__ , __magic_name__ , __magic_name__ : Dict =fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __magic_name__ , __magic_name__ , __magic_name__ : Any =fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __magic_name__ : str =model[0].eval() recursively_load_weights(lowerCamelCase , lowerCamelCase , lowerCamelCase ) hf_wavavec.save_pretrained(lowerCamelCase ) if __name__ == "__main__": UpperCAmelCase_ : Dict = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
367
import logging import os from dataclasses import dataclass, field from typing import Dict, Optional import datasets import numpy as np import tensorflow as tf from transformers import ( AutoConfig, AutoTokenizer, EvalPrediction, HfArgumentParser, PreTrainedTokenizer, TFAutoModelForSequenceClassification, TFTrainer, TFTrainingArguments, ) from transformers.utils import logging as hf_logging hf_logging.set_verbosity_info() hf_logging.enable_default_handler() hf_logging.enable_explicit_format() def lowerCAmelCase_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , ): __magic_name__ : Optional[int] ={} if train_file is not None: __magic_name__ : Optional[int] =[train_file] if eval_file is not None: __magic_name__ : Any =[eval_file] if test_file is not None: __magic_name__ : int =[test_file] __magic_name__ : Any =datasets.load_dataset("""csv""" , data_files=lowerCamelCase ) __magic_name__ : Optional[Any] =list(ds[list(files.keys() )[0]].features.keys() ) __magic_name__ : Optional[Any] =features_name.pop(lowerCamelCase ) __magic_name__ : str =list(set(ds[list(files.keys() )[0]][label_name] ) ) __magic_name__ : Union[str, Any] ={label: i for i, label in enumerate(lowerCamelCase )} __magic_name__ : Dict =tokenizer.model_input_names __magic_name__ : Any ={} if len(lowerCamelCase ) == 1: for k in files.keys(): __magic_name__ : Dict =ds[k].map( lambda lowerCamelCase : tokenizer.batch_encode_plus( example[features_name[0]] , truncation=lowerCamelCase , max_length=lowerCamelCase , padding="""max_length""" ) , batched=lowerCamelCase , ) elif len(lowerCamelCase ) == 2: for k in files.keys(): __magic_name__ : Optional[Any] =ds[k].map( lambda lowerCamelCase : tokenizer.batch_encode_plus( (example[features_name[0]], example[features_name[1]]) , truncation=lowerCamelCase , max_length=lowerCamelCase , padding="""max_length""" , ) , batched=lowerCamelCase , ) def gen_train(): for ex in transformed_ds[datasets.Split.TRAIN]: __magic_name__ : Any ={k: v for k, v in ex.items() if k in input_names} __magic_name__ : Any =labelaid[ex[label_name]] yield (d, label) def gen_val(): for ex in transformed_ds[datasets.Split.VALIDATION]: __magic_name__ : Dict ={k: v for k, v in ex.items() if k in input_names} __magic_name__ : str =labelaid[ex[label_name]] yield (d, label) def gen_test(): for ex in transformed_ds[datasets.Split.TEST]: __magic_name__ : Union[str, Any] ={k: v for k, v in ex.items() if k in input_names} __magic_name__ : Optional[int] =labelaid[ex[label_name]] yield (d, label) __magic_name__ : Union[str, Any] =( tf.data.Dataset.from_generator( lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TRAIN in transformed_ds else None ) if train_ds is not None: __magic_name__ : Optional[Any] =train_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TRAIN] ) ) ) __magic_name__ : Optional[Any] =( tf.data.Dataset.from_generator( lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.VALIDATION in transformed_ds else None ) if val_ds is not None: __magic_name__ : Any =val_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.VALIDATION] ) ) ) __magic_name__ : Any =( tf.data.Dataset.from_generator( lowerCamelCase , ({k: tf.intaa for k in input_names}, tf.intaa) , ({k: tf.TensorShape([None] ) for k in input_names}, tf.TensorShape([] )) , ) if datasets.Split.TEST in transformed_ds else None ) if test_ds is not None: __magic_name__ : Optional[int] =test_ds.apply(tf.data.experimental.assert_cardinality(len(ds[datasets.Split.TEST] ) ) ) return train_ds, val_ds, test_ds, labelaid UpperCAmelCase_ : int = logging.getLogger(__name__) @dataclass class __A : UpperCamelCase = field(metadata={"""help""": """Which column contains the label"""} ) UpperCamelCase = field(default=UpperCamelCase__ , metadata={"""help""": """The path of the training file"""} ) UpperCamelCase = field(default=UpperCamelCase__ , metadata={"""help""": """The path of the development file"""} ) UpperCamelCase = field(default=UpperCamelCase__ , metadata={"""help""": """The path of the test file"""} ) UpperCamelCase = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) UpperCamelCase = field( default=UpperCamelCase__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) @dataclass class __A : UpperCamelCase = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) UpperCamelCase = field( default=UpperCamelCase__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) UpperCamelCase = field( default=UpperCamelCase__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) UpperCamelCase = field(default=UpperCamelCase__ , 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. UpperCamelCase = field( default=UpperCamelCase__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) def lowerCAmelCase_ ( ): # 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. __magic_name__ : List[Any] =HfArgumentParser((ModelArguments, DataTrainingArguments, TFTrainingArguments) ) __magic_name__ , __magic_name__ , __magic_name__ : Union[str, Any] =parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F"Output directory ({training_args.output_dir}) already exists and is not empty. Use" """ --overwrite_output_dir to overcome.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , level=logging.INFO , ) logger.info( F"n_replicas: {training_args.n_replicas}, distributed training: {bool(training_args.n_replicas > 1 )}, " F"16-bits training: {training_args.fpaa}" ) logger.info(F"Training/evaluation parameters {training_args}" ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __magic_name__ : Dict =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 , ) __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ : Optional[Any] =get_tfds( train_file=data_args.train_file , eval_file=data_args.dev_file , test_file=data_args.test_file , tokenizer=lowerCamelCase , label_column_id=data_args.label_column_id , max_seq_length=data_args.max_seq_length , ) __magic_name__ : Any =AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=len(lowerCamelCase ) , labelaid=lowerCamelCase , idalabel={id: label for label, id in labelaid.items()} , finetuning_task="""text-classification""" , cache_dir=model_args.cache_dir , ) with training_args.strategy.scope(): __magic_name__ : Any =TFAutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_pt=bool(""".bin""" in model_args.model_name_or_path ) , config=lowerCamelCase , cache_dir=model_args.cache_dir , ) def compute_metrics(lowerCamelCase ) -> Dict: __magic_name__ : Tuple =np.argmax(p.predictions , axis=1 ) return {"acc": (preds == p.label_ids).mean()} # Initialize our Trainer __magic_name__ : int =TFTrainer( model=lowerCamelCase , args=lowerCamelCase , train_dataset=lowerCamelCase , eval_dataset=lowerCamelCase , compute_metrics=lowerCamelCase , ) # Training if training_args.do_train: trainer.train() trainer.save_model() tokenizer.save_pretrained(training_args.output_dir ) # Evaluation __magic_name__ : List[str] ={} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) __magic_name__ : List[str] =trainer.evaluate() __magic_name__ : Optional[Any] =os.path.join(training_args.output_dir , """eval_results.txt""" ) with open(lowerCamelCase , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in result.items(): logger.info(F" {key} = {value}" ) writer.write(F"{key} = {value}\n" ) results.update(lowerCamelCase ) return results if __name__ == "__main__": main()
367
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase__ = { 'tokenizer_file': { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json', }, } lowerCamelCase__ = { 'gpt-neox-20b': 20_48, } class UpperCamelCase ( snake_case__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["""input_ids""", """attention_mask"""] def __init__( self : Tuple ,_lowerCAmelCase : Dict=None ,_lowerCAmelCase : Union[str, Any]=None ,_lowerCAmelCase : List[str]=None ,_lowerCAmelCase : Any="<|endoftext|>" ,_lowerCAmelCase : Dict="<|endoftext|>" ,_lowerCAmelCase : Union[str, Any]="<|endoftext|>" ,_lowerCAmelCase : int=False ,**_lowerCAmelCase : List[str] ,): """simple docstring""" super().__init__( _lowerCAmelCase ,_lowerCAmelCase ,tokenizer_file=_lowerCAmelCase ,unk_token=_lowerCAmelCase ,bos_token=_lowerCAmelCase ,eos_token=_lowerCAmelCase ,add_prefix_space=_lowerCAmelCase ,**_lowerCAmelCase ,) __snake_case = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" ,_lowerCAmelCase ) != add_prefix_space: __snake_case = getattr(_lowerCAmelCase ,pre_tok_state.pop("type" ) ) __snake_case = add_prefix_space __snake_case = pre_tok_class(**_lowerCAmelCase ) __snake_case = add_prefix_space def UpperCamelCase_ ( self : int ,_lowerCAmelCase : str ,_lowerCAmelCase : Optional[str] = None ): """simple docstring""" __snake_case = self._tokenizer.model.save(_lowerCAmelCase ,name=_lowerCAmelCase ) return tuple(_lowerCAmelCase ) def UpperCamelCase_ ( self : str ,_lowerCAmelCase : "Conversation" ): """simple docstring""" __snake_case = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(_lowerCAmelCase ,add_special_tokens=_lowerCAmelCase ) + [self.eos_token_id] ) if len(_lowerCAmelCase ) > self.model_max_length: __snake_case = input_ids[-self.model_max_length :] return input_ids
524
import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase__ = logging.get_logger(__name__) def _lowerCamelCase( __snake_case , __snake_case ) -> Dict: __snake_case = [] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (f"""encoder.deit.blocks.{i}.norm1.weight""", f"""encoder.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""encoder.deit.blocks.{i}.norm1.bias""", f"""encoder.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.attn.proj.weight""", f"""encoder.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.attn.proj.bias""", f"""encoder.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.norm2.weight""", f"""encoder.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""encoder.deit.blocks.{i}.norm2.bias""", f"""encoder.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.mlp.fc1.weight""", f"""encoder.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.mlp.fc1.bias""", f"""encoder.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append( (f"""encoder.deit.blocks.{i}.mlp.fc2.weight""", f"""encoder.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""encoder.deit.blocks.{i}.mlp.fc2.bias""", f"""encoder.encoder.layer.{i}.output.dense.bias""") ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ("encoder.deit.cls_token", "encoder.embeddings.cls_token"), ("encoder.deit.pos_embed", "encoder.embeddings.position_embeddings"), ("encoder.deit.patch_embed.proj.weight", "encoder.embeddings.patch_embeddings.projection.weight"), ("encoder.deit.patch_embed.proj.bias", "encoder.embeddings.patch_embeddings.projection.bias"), ("encoder.deit.norm.weight", "encoder.layernorm.weight"), ("encoder.deit.norm.bias", "encoder.layernorm.bias"), ] ) return rename_keys def _lowerCamelCase( __snake_case , __snake_case ) -> Dict: for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) __snake_case = state_dict.pop(f"""encoder.deit.blocks.{i}.attn.qkv.weight""" ) __snake_case = in_proj_weight[ : encoder_config.hidden_size, : ] __snake_case = in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] __snake_case = in_proj_weight[ -encoder_config.hidden_size :, : ] def _lowerCamelCase( __snake_case , __snake_case , __snake_case ) -> List[Any]: __snake_case = dct.pop(__snake_case ) __snake_case = val def _lowerCamelCase( __snake_case ) -> str: if "handwritten" in checkpoint_url: __snake_case = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg" # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: __snake_case = "https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg" __snake_case = Image.open(requests.get(__snake_case , stream=__snake_case ).raw ).convert("RGB" ) return im @torch.no_grad() def _lowerCamelCase( __snake_case , __snake_case ) -> int: __snake_case = ViTConfig(image_size=384 , qkv_bias=__snake_case ) __snake_case = TrOCRConfig() # size of the architecture if "base" in checkpoint_url: __snake_case = 768 elif "large" in checkpoint_url: # use ViT-large encoder __snake_case = 1024 __snake_case = 4096 __snake_case = 24 __snake_case = 16 __snake_case = 1024 else: raise ValueError("Should either find 'base' or 'large' in checkpoint URL" ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: __snake_case = False __snake_case = "relu" __snake_case = 1024 __snake_case = True __snake_case = False __snake_case = False # load HuggingFace model __snake_case = ViTModel(__snake_case , add_pooling_layer=__snake_case ) __snake_case = TrOCRForCausalLM(__snake_case ) __snake_case = VisionEncoderDecoderModel(encoder=__snake_case , decoder=__snake_case ) model.eval() # load state_dict of original model, rename some keys __snake_case = torch.hub.load_state_dict_from_url(__snake_case , map_location="cpu" , check_hash=__snake_case )["model"] __snake_case = create_rename_keys(__snake_case , __snake_case ) for src, dest in rename_keys: rename_key(__snake_case , __snake_case , __snake_case ) read_in_q_k_v(__snake_case , __snake_case ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): __snake_case = state_dict.pop(__snake_case ) if key.startswith("decoder" ) and "output_projection" not in key: __snake_case = val else: __snake_case = val # load state dict model.load_state_dict(__snake_case ) # Check outputs on an image __snake_case = ViTImageProcessor(size=encoder_config.image_size ) __snake_case = RobertaTokenizer.from_pretrained("roberta-large" ) __snake_case = TrOCRProcessor(__snake_case , __snake_case ) __snake_case = processor(images=prepare_img(__snake_case ) , return_tensors="pt" ).pixel_values # verify logits __snake_case = torch.tensor([[model.config.decoder.decoder_start_token_id]] ) __snake_case = model(pixel_values=__snake_case , decoder_input_ids=__snake_case ) __snake_case = outputs.logits __snake_case = torch.Size([1, 1, 5_0265] ) if "trocr-base-handwritten" in checkpoint_url: __snake_case = torch.tensor( [-1.4_5_0_2, -4.6_6_8_3, -0.5_3_4_7, -2.9_2_9_1, 9.1_4_3_5, -3.0_5_7_1, 8.9_7_6_4, 1.7_5_6_0, 8.7_3_5_8, -1.5_3_1_1] ) elif "trocr-large-handwritten" in checkpoint_url: __snake_case = torch.tensor( [-2.6_4_3_7, -1.3_1_2_9, -2.2_5_9_6, -5.3_4_5_5, 6.3_5_3_9, 1.7_6_0_4, 5.4_9_9_1, 1.4_7_0_2, 5.6_1_1_3, 2.0_1_7_0] ) elif "trocr-base-printed" in checkpoint_url: __snake_case = torch.tensor( [-5.6_8_1_6, -5.8_3_8_8, 1.1_3_9_8, -6.9_0_3_4, 6.8_5_0_5, -2.4_3_9_3, 1.2_2_8_4, -1.0_2_3_2, -1.9_6_6_1, -3.9_2_1_0] ) elif "trocr-large-printed" in checkpoint_url: __snake_case = torch.tensor( [-6.0_1_6_2, -7.0_9_5_9, 4.4_1_5_5, -5.1_0_6_3, 7.0_4_6_8, -3.1_6_3_1, 2.6_4_6_6, -0.3_0_8_1, -0.8_1_0_6, -1.7_5_3_5] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10] , __snake_case , atol=1e-3 ), "First elements of logits not as expected" Path(__snake_case ).mkdir(exist_ok=__snake_case ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(__snake_case ) print(f"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(__snake_case ) if __name__ == "__main__": lowerCamelCase__ = argparse.ArgumentParser() parser.add_argument( '--checkpoint_url', default='https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt', type=str, help='URL to the original PyTorch checkpoint (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) lowerCamelCase__ = parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
524
1
"""simple docstring""" import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCamelCase__ ( SCREAMING_SNAKE_CASE ): '''simple docstring''' _lowerCamelCase = (EulerDiscreteScheduler,) _lowerCamelCase = 10 def UpperCamelCase__ ( self ,**lowerCamelCase_ ) -> Tuple: A = { """num_train_timesteps""": 1_1_0_0, """beta_start""": 0.00_01, """beta_end""": 0.02, """beta_schedule""": """linear""", } config.update(**lowerCamelCase_ ) return config def UpperCamelCase__ ( self ) -> int: for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> List[str]: for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01] ,[0.00_02, 0.0_02, 0.02] ): self.check_over_configs(beta_start=lowerCamelCase_ ,beta_end=lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> Union[str, Any]: for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> str: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowerCamelCase_ ) def UpperCamelCase__ ( self ) -> Tuple: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(self.num_inference_steps ) A = torch.manual_seed(0 ) A = self.dummy_model() A = self.dummy_sample_deter * scheduler.init_noise_sigma A = sample.to(lowerCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): A = scheduler.scale_model_input(lowerCamelCase_ ,lowerCamelCase_ ) A = model(lowerCamelCase_ ,lowerCamelCase_ ) A = scheduler.step(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,generator=lowerCamelCase_ ) A = output.prev_sample A = torch.sum(torch.abs(lowerCamelCase_ ) ) A = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_sum.item() - 10.08_07 ) < 1E-2 assert abs(result_mean.item() - 0.01_31 ) < 1E-3 def UpperCamelCase__ ( self ) -> List[str]: A = self.scheduler_classes[0] A = self.get_scheduler_config(prediction_type="""v_prediction""" ) A = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(self.num_inference_steps ) A = torch.manual_seed(0 ) A = self.dummy_model() A = self.dummy_sample_deter * scheduler.init_noise_sigma A = sample.to(lowerCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): A = scheduler.scale_model_input(lowerCamelCase_ ,lowerCamelCase_ ) A = model(lowerCamelCase_ ,lowerCamelCase_ ) A = scheduler.step(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,generator=lowerCamelCase_ ) A = output.prev_sample A = torch.sum(torch.abs(lowerCamelCase_ ) ) A = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_sum.item() - 0.00_02 ) < 1E-2 assert abs(result_mean.item() - 2.2676E-06 ) < 1E-3 def UpperCamelCase__ ( self ) -> Dict: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**lowerCamelCase_ ) scheduler.set_timesteps(self.num_inference_steps ,device=lowerCamelCase_ ) A = torch.manual_seed(0 ) A = self.dummy_model() A = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() A = sample.to(lowerCamelCase_ ) for t in scheduler.timesteps: A = scheduler.scale_model_input(lowerCamelCase_ ,lowerCamelCase_ ) A = model(lowerCamelCase_ ,lowerCamelCase_ ) A = scheduler.step(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,generator=lowerCamelCase_ ) A = output.prev_sample A = torch.sum(torch.abs(lowerCamelCase_ ) ) A = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_sum.item() - 10.08_07 ) < 1E-2 assert abs(result_mean.item() - 0.01_31 ) < 1E-3 def UpperCamelCase__ ( self ) -> int: A = self.scheduler_classes[0] A = self.get_scheduler_config() A = scheduler_class(**lowerCamelCase_ ,use_karras_sigmas=lowerCamelCase_ ) scheduler.set_timesteps(self.num_inference_steps ,device=lowerCamelCase_ ) A = torch.manual_seed(0 ) A = self.dummy_model() A = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() A = sample.to(lowerCamelCase_ ) for t in scheduler.timesteps: A = scheduler.scale_model_input(lowerCamelCase_ ,lowerCamelCase_ ) A = model(lowerCamelCase_ ,lowerCamelCase_ ) A = scheduler.step(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ ,generator=lowerCamelCase_ ) A = output.prev_sample A = torch.sum(torch.abs(lowerCamelCase_ ) ) A = torch.mean(torch.abs(lowerCamelCase_ ) ) assert abs(result_sum.item() - 1_2_4.5_2_2_9_9_4_9_9_5_1_1_7_1_9 ) < 1E-2 assert abs(result_mean.item() - 0.1_62_13_93_26_33_39_99_63 ) < 1E-3
719
"""simple docstring""" UpperCAmelCase =256 # Modulus to hash a string UpperCAmelCase =1_000_003 def _A ( _a : str , _a : str ): """simple docstring""" A = len(_a ) A = len(_a ) if p_len > t_len: return False A = 0 A = 0 A = 1 # Calculating the hash of pattern and substring of text for i in range(_a ): A = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus A = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue A = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash A = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def _A ( ): """simple docstring""" A = """abc1abc12""" A = """alskfjaldsabc1abc1abc12k23adsfabcabc""" A = """alskfjaldsk23adsfabcabc""" assert rabin_karp(_a , _a ) and not rabin_karp(_a , _a ) # Test 2) A = """ABABX""" A = """ABABZABABYABABX""" assert rabin_karp(_a , _a ) # Test 3) A = """AAAB""" A = """ABAAAAAB""" assert rabin_karp(_a , _a ) # Test 4) A = """abcdabcy""" A = """abcxabcdabxabcdabcdabcy""" assert rabin_karp(_a , _a ) # Test 5) A = """Lü""" A = """Lüsai""" assert rabin_karp(_a , _a ) A = """Lue""" assert not rabin_karp(_a , _a ) print("""Success.""" ) if __name__ == "__main__": test_rabin_karp()
255
0
import math def a ( snake_case__: list , snake_case__: int ): '''simple docstring''' lowercase_ = len(snake_case__ ) lowercase_ = int(math.floor(math.sqrt(snake_case__ ) ) ) lowercase_ = 0 while arr[min(snake_case__ , snake_case__ ) - 1] < x: lowercase_ = step step += int(math.floor(math.sqrt(snake_case__ ) ) ) if prev >= n: return -1 while arr[prev] < x: lowercase_ = prev + 1 if prev == min(snake_case__ , snake_case__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": __a = input('Enter numbers separated by a comma:\n').strip() __a = [int(item) for item in user_input.split(',')] __a = int(input('Enter the number to be searched:\n')) __a = jump_search(arr, x) if res == -1: print('Number not found!') else: print(f"Number {x} is at index {res}")
97
"""simple docstring""" import inspect import unittest from transformers import ConvNextConfig 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_backbone_common import BackboneTesterMixin 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 ConvNextBackbone, ConvNextForImageClassification, ConvNextModel from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ : '''simple docstring''' def __init__( self : Any , lowercase_ : str , lowercase_ : Dict=13 , lowercase_ : Dict=32 , lowercase_ : Any=3 , lowercase_ : Any=4 , lowercase_ : int=[10, 20, 30, 40] , lowercase_ : Union[str, Any]=[2, 2, 3, 2] , lowercase_ : Optional[int]=True , lowercase_ : Union[str, Any]=True , lowercase_ : Dict=37 , lowercase_ : Optional[Any]="gelu" , lowercase_ : Union[str, Any]=10 , lowercase_ : Optional[int]=0.02 , lowercase_ : Tuple=["stage2", "stage3", "stage4"] , lowercase_ : Optional[Any]=[2, 3, 4] , lowercase_ : Optional[int]=None , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = parent SCREAMING_SNAKE_CASE_ : Any = batch_size SCREAMING_SNAKE_CASE_ : List[Any] = image_size SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE_ : List[Any] = num_stages SCREAMING_SNAKE_CASE_ : List[str] = hidden_sizes SCREAMING_SNAKE_CASE_ : Optional[int] = depths SCREAMING_SNAKE_CASE_ : str = is_training SCREAMING_SNAKE_CASE_ : int = use_labels SCREAMING_SNAKE_CASE_ : Dict = intermediate_size SCREAMING_SNAKE_CASE_ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE_ : List[Any] = initializer_range SCREAMING_SNAKE_CASE_ : Dict = out_features SCREAMING_SNAKE_CASE_ : List[str] = out_indices SCREAMING_SNAKE_CASE_ : int = scope def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) SCREAMING_SNAKE_CASE_ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.num_labels) SCREAMING_SNAKE_CASE_ : Optional[Any] = self.get_config() return config, pixel_values, labels def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' return ConvNextConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=lowercase_ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def _SCREAMING_SNAKE_CASE ( self : str , lowercase_ : Union[str, Any] , lowercase_ : Optional[Any] , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ConvNextModel(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) # 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 _SCREAMING_SNAKE_CASE ( self : Optional[int] , lowercase_ : str , lowercase_ : Dict , lowercase_ : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ConvNextForImageClassification(lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : List[Any] = model(lowercase_ , labels=lowercase_) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def _SCREAMING_SNAKE_CASE ( self : Tuple , lowercase_ : Union[str, Any] , lowercase_ : Any , lowercase_ : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : int = ConvNextBackbone(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Any = model(lowercase_) # verify hidden states self.parent.assertEqual(len(result.feature_maps) , len(config.out_features)) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[1], 4, 4]) # verify channels self.parent.assertEqual(len(model.channels) , len(config.out_features)) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:]) # verify backbone works with out_features=None SCREAMING_SNAKE_CASE_ : Optional[Any] = None SCREAMING_SNAKE_CASE_ : Union[str, Any] = ConvNextBackbone(config=lowercase_) model.to(lowercase_) model.eval() SCREAMING_SNAKE_CASE_ : Union[str, Any] = model(lowercase_) # verify feature maps self.parent.assertEqual(len(result.feature_maps) , 1) self.parent.assertListEqual(list(result.feature_maps[0].shape) , [self.batch_size, self.hidden_sizes[-1], 1, 1]) # verify channels self.parent.assertEqual(len(model.channels) , 1) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]]) def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : str = config_and_inputs SCREAMING_SNAKE_CASE_ : Dict = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' __UpperCamelCase = ( ( ConvNextModel, ConvNextForImageClassification, ConvNextBackbone, ) if is_torch_available() else () ) __UpperCamelCase = ( {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification} if is_torch_available() else {} ) __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = ConvNextModelTester(self) SCREAMING_SNAKE_CASE_ : int = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ , hidden_size=37) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' return @unittest.skip(reason='''ConvNext does not use inputs_embeds''') def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' pass @unittest.skip(reason='''ConvNext does not support input and output embeddings''') def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' pass @unittest.skip(reason='''ConvNext does not use feedforward chunking''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE_ : Dict = model_class(lowercase_) SCREAMING_SNAKE_CASE_ : int = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE_ : List[str] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE_ : int = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : str): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' def check_hidden_states_output(lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str): SCREAMING_SNAKE_CASE_ : Union[str, Any] = model_class(lowercase_) model.to(lowercase_) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE_ : List[Any] = model(**self._prepare_for_class(lowercase_ , lowercase_)) SCREAMING_SNAKE_CASE_ : Tuple = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.num_stages self.assertEqual(len(lowercase_) , expected_num_stages + 1) # ConvNext'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] , ) 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_ : Tuple = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE_ : str = True check_hidden_states_output(lowercase_ , lowercase_ , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_) @slow def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE_ : int = ConvNextModel.from_pretrained(lowercase_) self.assertIsNotNone(lowercase_) def _A () -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def _SCREAMING_SNAKE_CASE ( self : List[str]): '''simple docstring''' return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224''') if is_vision_available() else None @slow def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Any = ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224''').to(lowercase_) SCREAMING_SNAKE_CASE_ : str = self.default_image_processor SCREAMING_SNAKE_CASE_ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE_ : List[Any] = image_processor(images=lowercase_ , return_tensors='''pt''').to(lowercase_) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE_ : str = model(**lowercase_) # verify the logits SCREAMING_SNAKE_CASE_ : List[Any] = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape , lowercase_) SCREAMING_SNAKE_CASE_ : int = torch.tensor([-0.02_60, -0.47_39, 0.19_11]).to(lowercase_) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase_ , atol=1e-4)) @require_torch class lowerCAmelCase__ ( unittest.TestCase , UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = (ConvNextBackbone,) if is_torch_available() else () __UpperCamelCase = ConvNextConfig __UpperCamelCase = False def _SCREAMING_SNAKE_CASE ( self : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = ConvNextModelTester(self)
512
0
from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
381
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__( __lowercase ): '''simple docstring''' __snake_case = 42 class lowerCAmelCase__( __lowercase , __lowercase ): '''simple docstring''' @register_to_config def __init__( self , __lowerCamelCase = 3 , __lowerCamelCase = 3 , __lowerCamelCase = ("DownEncoderBlock2D",) , __lowerCamelCase = ("UpDecoderBlock2D",) , __lowerCamelCase = (6_4,) , __lowerCamelCase = 1 , __lowerCamelCase = "silu" , __lowerCamelCase = 3 , __lowerCamelCase = 3_2 , __lowerCamelCase = 2_5_6 , __lowerCamelCase = 3_2 , __lowerCamelCase = None , __lowerCamelCase = 0.1_8215 , __lowerCamelCase = "group" , ) -> List[str]: super().__init__() # pass init params to Encoder _SCREAMING_SNAKE_CASE : Tuple = Encoder( in_channels=__lowerCamelCase , out_channels=__lowerCamelCase , down_block_types=__lowerCamelCase , block_out_channels=__lowerCamelCase , layers_per_block=__lowerCamelCase , act_fn=__lowerCamelCase , norm_num_groups=__lowerCamelCase , double_z=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE : Dict = vq_embed_dim if vq_embed_dim is not None else latent_channels _SCREAMING_SNAKE_CASE : str = nn.Convad(__lowerCamelCase , __lowerCamelCase , 1 ) _SCREAMING_SNAKE_CASE : Tuple = VectorQuantizer(__lowerCamelCase , __lowerCamelCase , beta=0.25 , remap=__lowerCamelCase , sane_index_shape=__lowerCamelCase ) _SCREAMING_SNAKE_CASE : int = nn.Convad(__lowerCamelCase , __lowerCamelCase , 1 ) # pass init params to Decoder _SCREAMING_SNAKE_CASE : Dict = Decoder( in_channels=__lowerCamelCase , out_channels=__lowerCamelCase , up_block_types=__lowerCamelCase , block_out_channels=__lowerCamelCase , layers_per_block=__lowerCamelCase , act_fn=__lowerCamelCase , norm_num_groups=__lowerCamelCase , norm_type=__lowerCamelCase , ) @apply_forward_hook def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = True ) -> VQEncoderOutput: _SCREAMING_SNAKE_CASE : Optional[int] = self.encoder(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Any = self.quant_conv(__lowerCamelCase ) if not return_dict: return (h,) return VQEncoderOutput(latents=__lowerCamelCase ) @apply_forward_hook def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = False , __lowerCamelCase = True ) -> Union[DecoderOutput, torch.FloatTensor]: # also go through quantization layer if not force_not_quantize: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[int] = self.quantize(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE : Dict = h _SCREAMING_SNAKE_CASE : str = self.post_quant_conv(__lowerCamelCase ) _SCREAMING_SNAKE_CASE : Dict = self.decoder(__lowerCamelCase , quant if self.config.norm_type == "spatial" else None ) if not return_dict: return (dec,) return DecoderOutput(sample=__lowerCamelCase ) def UpperCamelCase_ ( self , __lowerCamelCase , __lowerCamelCase = True ) -> Union[DecoderOutput, torch.FloatTensor]: _SCREAMING_SNAKE_CASE : List[Any] = sample _SCREAMING_SNAKE_CASE : List[str] = self.encode(__lowerCamelCase ).latents _SCREAMING_SNAKE_CASE : List[str] = self.decode(__lowerCamelCase ).sample if not return_dict: return (dec,) return DecoderOutput(sample=__lowerCamelCase )
381
1
import unittest from transformers.testing_utils import require_bsa from transformers.utils import is_bsa_available from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin if is_bsa_available(): from transformers import MarkupLMFeatureExtractor class __magic_name__ ( unittest.TestCase ): """simple docstring""" def __init__( self :Any , snake_case :Optional[int] ): '''simple docstring''' A_ : str = parent def SCREAMING_SNAKE_CASE ( self :Any ): '''simple docstring''' return {} def __snake_case ( ) -> int: A_ : Tuple = "<HTML>\n\n <HEAD>\n <TITLE>sample document</TITLE>\n </HEAD>\n\n <BODY BGCOLOR=\"FFFFFF\">\n <HR>\n <a href=\"http://google.com\">Goog</a>\n <H1>This is one header</H1>\n <H2>This is a another Header</H2>\n <P>Travel from\n <P>\n <B>SFO to JFK</B>\n <BR>\n <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n <HR>\n <div style=\"color:#0000FF\">\n <h3>Traveler <b> name </b> is\n <p> John Doe </p>\n </div>" A_ : int = "\n <!DOCTYPE html>\n <html>\n <body>\n\n <h1>My First Heading</h1>\n <p>My first paragraph.</p>\n\n </body>\n </html>\n " return [html_string_a, html_string_a] @require_bsa class __magic_name__ ( lowerCamelCase__ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = MarkupLMFeatureExtractor if is_bsa_available() else None def SCREAMING_SNAKE_CASE ( self :List[Any] ): '''simple docstring''' A_ : Optional[int] = MarkupLMFeatureExtractionTester(self ) @property def SCREAMING_SNAKE_CASE ( self :str ): '''simple docstring''' return self.feature_extract_tester.prepare_feat_extract_dict() def SCREAMING_SNAKE_CASE ( self :Union[str, Any] ): '''simple docstring''' A_ : Optional[int] = self.feature_extraction_class() # Test not batched input A_ : str = get_html_strings()[0] A_ : Tuple = feature_extractor(snake_case ) # fmt: off A_ : Any = [["sample document", "Goog", "This is one header", "This is a another Header", "Travel from", "SFO to JFK", "on May 2, 2015 at 2:00 pm. For details go to confirm.com", "Traveler", "name", "is", "John Doe"]] A_ : Tuple = [["/html/head/title", "/html/body/a", "/html/body/h1", "/html/body/h2", "/html/body/p", "/html/body/p/p/b[1]", "/html/body/p/p/b[2]/i", "/html/body/p/p/div/h3", "/html/body/p/p/div/h3/b", "/html/body/p/p/div/h3", "/html/body/p/p/div/h3/p"]] # fmt: on self.assertEqual(encoding.nodes , snake_case ) self.assertEqual(encoding.xpaths , snake_case ) # Test batched A_ : Tuple = get_html_strings() A_ : List[str] = feature_extractor(snake_case ) # fmt: off A_ : str = expected_nodes + [["My First Heading", "My first paragraph."]] A_ : Tuple = expected_xpaths + [["/html/body/h1", "/html/body/p"]] self.assertEqual(len(encoding.nodes ) , 2 ) self.assertEqual(len(encoding.xpaths ) , 2 ) self.assertEqual(encoding.nodes , snake_case ) self.assertEqual(encoding.xpaths , snake_case )
454
def __snake_case ( _lowerCAmelCase : int = 1 , _lowerCAmelCase : int = 1000 ) -> int: A_ : Optional[int] = 1 A_ : int = 0 for divide_by_number in range(_lowerCAmelCase , digit + 1 ): A_ : list[int] = [] A_ : Union[str, Any] = numerator for _ in range(1 , digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(_lowerCAmelCase ): A_ : Optional[Any] = len(_lowerCAmelCase ) A_ : Union[str, Any] = divide_by_number else: has_been_divided.append(_lowerCAmelCase ) A_ : Dict = now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
454
1
"""simple docstring""" def __A ( a_ :int) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('''The given input must be positive''') # get the generated string sequence __a : int = gray_code_sequence_string(a_) # # convert them to integers for i in range(len(a_)): __a : Union[str, Any] = int(sequence[i] , 2) return sequence def __A ( a_ :int) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] __a : Optional[Any] = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits __a : Any = gray_code_sequence_string(bit_count - 1) __a : Optional[int] = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2): __a : List[Any] = '''0''' + smaller_sequence[i] sequence.append(a_) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2)): __a : int = '''1''' + smaller_sequence[i] sequence.append(a_) return sequence if __name__ == "__main__": import doctest doctest.testmod()
716
"""simple docstring""" 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 __lowercase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = StableDiffusionInstructPixaPixPipeline __lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''cross_attention_kwargs'''} __lowerCAmelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS __lowerCAmelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS __lowerCAmelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def _lowerCamelCase ( self ): torch.manual_seed(0 ) __a : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) __a : List[str] = PNDMScheduler(skip_prk_steps=_UpperCAmelCase ) torch.manual_seed(0 ) __a : int = 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 ) __a : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __a : Optional[int] = CLIPTextModel(_UpperCAmelCase ) __a : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __a : Union[str, Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def _lowerCamelCase ( self , _UpperCAmelCase , _UpperCAmelCase=0 ): __a : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(_UpperCAmelCase ) ).to(_UpperCAmelCase ) __a : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] __a : Tuple = Image.fromarray(np.uinta(_UpperCAmelCase ) ).convert('''RGB''' ) if str(_UpperCAmelCase ).startswith('''mps''' ): __a : Union[str, Any] = torch.manual_seed(_UpperCAmelCase ) else: __a : Union[str, Any] = torch.Generator(device=_UpperCAmelCase ).manual_seed(_UpperCAmelCase ) __a : Union[str, 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 _lowerCamelCase ( self ): __a : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __a : Dict = self.get_dummy_components() __a : Any = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) __a : int = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) __a : Union[str, Any] = self.get_dummy_inputs(_UpperCAmelCase ) __a : str = sd_pipe(**_UpperCAmelCase ).images __a : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __a : 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 _lowerCamelCase ( self ): __a : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator __a : Optional[Any] = self.get_dummy_components() __a : Dict = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) __a : List[Any] = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) __a : Dict = self.get_dummy_inputs(_UpperCAmelCase ) __a : Union[str, Any] = '''french fries''' __a : str = sd_pipe(**_UpperCAmelCase , negative_prompt=_UpperCAmelCase ) __a : Dict = output.images __a : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __a : Tuple = 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 _lowerCamelCase ( self ): __a : Union[str, Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator __a : Dict = self.get_dummy_components() __a : str = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) __a : Optional[int] = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) __a : Union[str, Any] = self.get_dummy_inputs(_UpperCAmelCase ) __a : List[str] = [inputs['''prompt''']] * 2 __a : Optional[Any] = np.array(inputs['''image'''] ).astype(np.floataa ) / 2_5_5.0 __a : Optional[Any] = torch.from_numpy(_UpperCAmelCase ).unsqueeze(0 ).to(_UpperCAmelCase ) __a : Tuple = image / 2 + 0.5 __a : str = image.permute(0 , 3 , 1 , 2 ) __a : List[str] = image.repeat(2 , 1 , 1 , 1 ) __a : int = sd_pipe(**_UpperCAmelCase ).images __a : Optional[Any] = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) __a : List[str] = 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 _lowerCamelCase ( self ): __a : Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator __a : List[str] = self.get_dummy_components() __a : Union[str, Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' ) __a : str = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) __a : List[str] = sd_pipe.to(_UpperCAmelCase ) sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase ) __a : Dict = self.get_dummy_inputs(_UpperCAmelCase ) __a : Any = sd_pipe(**_UpperCAmelCase ).images __a : Dict = image[0, -3:, -3:, -1] __a : Optional[int] = [round(_UpperCAmelCase , 4 ) for x in image_slice.flatten().tolist()] print(''','''.join([str(_UpperCAmelCase ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) __a : int = 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 _lowerCamelCase ( self ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def _lowerCamelCase ( self ): __a : Any = self.get_dummy_components() __a : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**_UpperCAmelCase ) __a : Any = VaeImageProcessor(do_resize=_UpperCAmelCase , do_normalize=_UpperCAmelCase ) __a : Dict = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) __a : str = pipe(**self.get_dummy_inputs_by_type(_UpperCAmelCase , input_image_type='''pt''' ) )[0] __a : List[Any] = components['''vae'''] __a : List[Any] = self.get_dummy_inputs_by_type(_UpperCAmelCase , input_image_type='''pt''' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): __a : Optional[Any] = vae.encode(inputs[image_param] ).latent_dist.mode() __a : str = pipe(**_UpperCAmelCase )[0] __a : Union[str, Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(_UpperCAmelCase , 1e-4 , '''passing latents as image input generate different result from passing image''' ) @slow @require_torch_gpu class __lowercase ( unittest.TestCase ): '''simple docstring''' def _lowerCamelCase ( self ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowerCamelCase ( self , _UpperCAmelCase=0 ): __a : List[str] = torch.manual_seed(_UpperCAmelCase ) __a : str = load_image( '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg''' ) __a : List[str] = { '''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 _lowerCamelCase ( self ): __a : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() __a : str = self.get_inputs() __a : Optional[Any] = pipe(**_UpperCAmelCase ).images __a : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __a : Tuple = 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 _lowerCamelCase ( self ): __a : Tuple = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_UpperCAmelCase ) __a : Optional[int] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() __a : List[str] = self.get_inputs() __a : Optional[int] = pipe(**_UpperCAmelCase ).images __a : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __a : Tuple = 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 _lowerCamelCase ( self ): __a : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_UpperCAmelCase ) __a : Optional[int] = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() __a : List[str] = self.get_inputs() __a : str = pipe(**_UpperCAmelCase ).images __a : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __a : Any = 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 _lowerCamelCase ( self ): __a : Dict = 0 def callback_fn(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> None: __a : Optional[Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: __a : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) __a : int = latents[0, -3:, -3:, -1] __a : int = 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: __a : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) __a : List[str] = latents[0, -3:, -3:, -1] __a : Tuple = 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 __a : Union[str, Any] = False __a : Optional[int] = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_UpperCAmelCase , torch_dtype=torch.floataa ) __a : Optional[int] = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() __a : str = self.get_inputs() pipe(**_UpperCAmelCase , callback=_UpperCAmelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def _lowerCamelCase ( self ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __a : Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( '''timbrooks/instruct-pix2pix''' , safety_checker=_UpperCAmelCase , torch_dtype=torch.floataa ) __a : Optional[int] = pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __a : List[Any] = self.get_inputs() __a : Tuple = pipe(**_UpperCAmelCase ) __a : List[str] = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def _lowerCamelCase ( self ): __a : List[Any] = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 __a : str = inputs['''image'''].resize((504, 504) ) __a : Tuple = '''timbrooks/instruct-pix2pix''' __a : Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( _UpperCAmelCase , safety_checker=_UpperCAmelCase , ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) pipe.enable_attention_slicing() __a : List[Any] = pipe(**_UpperCAmelCase ) __a : int = output.images[0] __a : Optional[int] = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) __a : 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
101
0
def lowerCAmelCase__ ( a__: int = 1_0_0_0 ) -> int: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = 1, 1 _UpperCAmelCase = 2 while True: _UpperCAmelCase = 0 _UpperCAmelCase = fa + fa _UpperCAmelCase , _UpperCAmelCase = fa, f index += 1 for _ in str(a__ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
618
import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE=0.01 , _SCREAMING_SNAKE_CASE=1000 ) -> str: """simple docstring""" _UpperCAmelCase = p_stop _UpperCAmelCase = max_length def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = 0 _UpperCAmelCase = False while not stop and count < self.max_length: yield count count += 1 _UpperCAmelCase = random.random() < self.p_stop class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True ) -> int: """simple docstring""" _UpperCAmelCase = [ BatchSamplerShard(_SCREAMING_SNAKE_CASE , 2 , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) for i in range(2 ) ] _UpperCAmelCase = [list(_SCREAMING_SNAKE_CASE ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(_SCREAMING_SNAKE_CASE ) for shard in batch_sampler_shards] , [len(_SCREAMING_SNAKE_CASE ) for e in expected] ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = BatchSampler(range(24 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(24 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) # Expected shouldn't change self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. _UpperCAmelCase = BatchSampler(range(21 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(21 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. _UpperCAmelCase = BatchSampler(range(22 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(22 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. _UpperCAmelCase = BatchSampler(range(20 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(20 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is very small. _UpperCAmelCase = BatchSampler(range(2 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(2 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[], []] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = BatchSampler(range(24 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(24 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) # Expected shouldn't change self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is not a round multiple of batch size. _UpperCAmelCase = BatchSampler(range(22 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(22 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. _UpperCAmelCase = BatchSampler(range(21 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(21 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is very small. _UpperCAmelCase = BatchSampler(range(2 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(2 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[], []] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = BatchSampler(range(24 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(24 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) # Expected shouldn't change self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. _UpperCAmelCase = BatchSampler(range(21 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(21 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. _UpperCAmelCase = BatchSampler(range(22 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(22 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. _UpperCAmelCase = BatchSampler(range(20 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(20 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is very small. _UpperCAmelCase = BatchSampler(range(2 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[[0, 1]], []] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(2 ) , batch_size=3 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[], []] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = BatchSampler(range(24 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(24 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) # Expected shouldn't change self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is not a round multiple of batch size. _UpperCAmelCase = BatchSampler(range(22 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(22 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. _UpperCAmelCase = BatchSampler(range(21 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(21 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) # Check the shards when the dataset is very small. _UpperCAmelCase = BatchSampler(range(2 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[[0, 1]], []] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = BatchSampler(range(2 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[], []] self.check_batch_sampler_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] _UpperCAmelCase = [BatchSamplerShard(_SCREAMING_SNAKE_CASE , 2 , _SCREAMING_SNAKE_CASE , even_batches=_SCREAMING_SNAKE_CASE ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=False ) -> Dict: """simple docstring""" random.seed(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ IterableDatasetShard( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , drop_last=_SCREAMING_SNAKE_CASE , num_processes=_SCREAMING_SNAKE_CASE , process_index=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE , ) for i in range(_SCREAMING_SNAKE_CASE ) ] _UpperCAmelCase = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(_SCREAMING_SNAKE_CASE ) iterable_dataset_lists.append(list(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size _UpperCAmelCase = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(len(_SCREAMING_SNAKE_CASE ) % shard_batch_size == 0 ) _UpperCAmelCase = [] for idx in range(0 , len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(_SCREAMING_SNAKE_CASE ) < len(_SCREAMING_SNAKE_CASE ): reference += reference self.assertListEqual(_SCREAMING_SNAKE_CASE , reference[: len(_SCREAMING_SNAKE_CASE )] ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = 42 _UpperCAmelCase = RandomIterableDataset() self.check_iterable_dataset_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) self.check_iterable_dataset_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) self.check_iterable_dataset_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) self.check_iterable_dataset_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) # Edge case with a very small dataset _UpperCAmelCase = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) self.check_iterable_dataset_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) self.check_iterable_dataset_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) self.check_iterable_dataset_shards(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE , split_batches=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = BatchSampler(range(16 ) , batch_size=4 , drop_last=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = SkipBatchSampler(_SCREAMING_SNAKE_CASE , 2 ) self.assertListEqual(list(_SCREAMING_SNAKE_CASE ) , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = DataLoader(list(range(16 ) ) , batch_size=4 ) _UpperCAmelCase = skip_first_batches(_SCREAMING_SNAKE_CASE , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = DataLoaderShard(list(range(16 ) ) , batch_size=4 ) for idx, _ in enumerate(_SCREAMING_SNAKE_CASE ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(_SCREAMING_SNAKE_CASE ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" Accelerator() _UpperCAmelCase = DataLoaderDispatcher(range(16 ) , batch_size=4 ) for idx, _ in enumerate(_SCREAMING_SNAKE_CASE ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(_SCREAMING_SNAKE_CASE ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
618
1
import pytest from datasets import inspect_metric, list_metrics, load_metric @pytest.fixture def A__ ( SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: monkeypatch.setattr('''datasets.utils.deprecation_utils._emitted_deprecation_warnings''' , set() ) @pytest.fixture def A__ ( SCREAMING_SNAKE_CASE_ ) -> List[Any]: class snake_case_ : def __init__( self , __lowercase ) -> Tuple: lowerCamelCase : Tuple =metric_id class snake_case_ : lowerCamelCase :List[Any] = [MetricMock(__SCREAMING_SNAKE_CASE) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]] def __lowercase ( self ) -> List[str]: return self._metrics monkeypatch.setattr('''datasets.inspect.huggingface_hub''' , HfhMock() ) @pytest.mark.parametrize( '''func, args''' , [(load_metric, ('''metrics/mse''',)), (list_metrics, ()), (inspect_metric, ('''metrics/mse''', '''tmp_path'''))] ) def A__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: if "tmp_path" in args: lowerCamelCase : Any =tuple(arg if arg != '''tmp_path''' else tmp_path for arg in args ) with pytest.warns(a_ , match='''https://huggingface.co/docs/evaluate''' ): func(*a_ )
705
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { '''facebook/timesformer''': '''https://huggingface.co/facebook/timesformer/resolve/main/config.json''', } class snake_case_ ( _A): lowerCamelCase :Union[str, Any] = "timesformer" def __init__( self , __lowercase=2_2_4 , __lowercase=1_6 , __lowercase=3 , __lowercase=8 , __lowercase=7_6_8 , __lowercase=1_2 , __lowercase=1_2 , __lowercase=3_0_7_2 , __lowercase="gelu" , __lowercase=0.0 , __lowercase=0.0 , __lowercase=0.0_2 , __lowercase=1e-6 , __lowercase=True , __lowercase="divided_space_time" , __lowercase=0 , **__lowercase , ) -> List[Any]: super().__init__(**__lowercase ) lowerCamelCase : int =image_size lowerCamelCase : List[str] =patch_size lowerCamelCase : Union[str, Any] =num_channels lowerCamelCase : str =num_frames lowerCamelCase : Dict =hidden_size lowerCamelCase : int =num_hidden_layers lowerCamelCase : Dict =num_attention_heads lowerCamelCase : Dict =intermediate_size lowerCamelCase : Union[str, Any] =hidden_act lowerCamelCase : str =hidden_dropout_prob lowerCamelCase : Union[str, Any] =attention_probs_dropout_prob lowerCamelCase : List[Any] =initializer_range lowerCamelCase : List[Any] =layer_norm_eps lowerCamelCase : List[str] =qkv_bias lowerCamelCase : Tuple =attention_type lowerCamelCase : List[Any] =drop_path_rate
262
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging UpperCAmelCase = logging.get_logger(__name__) UpperCAmelCase = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class A_ ( __lowerCamelCase ): '''simple docstring''' _UpperCamelCase : Optional[int] = """data2vec-text""" def __init__( self , snake_case=3_0522 , snake_case=768 , snake_case=12 , snake_case=12 , snake_case=3072 , snake_case="gelu" , snake_case=0.1 , snake_case=0.1 , snake_case=512 , snake_case=2 , snake_case=0.02 , snake_case=1E-12 , snake_case=1 , snake_case=0 , snake_case=2 , snake_case="absolute" , snake_case=True , snake_case=None , **snake_case , ): super().__init__(pad_token_id=snake_case , bos_token_id=snake_case , eos_token_id=snake_case , **snake_case ) lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = hidden_act lowercase = intermediate_size lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = type_vocab_size lowercase = initializer_range lowercase = layer_norm_eps lowercase = position_embedding_type lowercase = use_cache lowercase = classifier_dropout class A_ ( __lowerCamelCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE__ ( self ): if self.task == "multiple-choice": lowercase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: lowercase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
84
'''simple docstring''' from math import sqrt def UpperCAmelCase_ ( lowerCAmelCase_ ): """simple docstring""" lowercase = 0 for i in range(1 , int(sqrt(lowerCAmelCase_ ) + 1 ) ): if n % i == 0 and i != sqrt(lowerCAmelCase_ ): total += i + n // i elif i == sqrt(lowerCAmelCase_ ): total += i return total - n def UpperCAmelCase_ ( lowerCAmelCase_ = 1_0000 ): """simple docstring""" lowercase = sum( i for i in range(1 , lowerCAmelCase_ ) if sum_of_divisors(sum_of_divisors(lowerCAmelCase_ ) ) == i and sum_of_divisors(lowerCAmelCase_ ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
310
0
from __future__ import annotations import queue class __lowerCamelCase : """simple docstring""" def __init__( self : str , lowerCamelCase_ : Optional[Any] ): _lowerCAmelCase =data _lowerCAmelCase =None _lowerCAmelCase =None def snake_case_ ( ): '''simple docstring''' print("""\n********Press N to stop entering at any point of time********\n""" ) _lowerCAmelCase =input("""Enter the value of the root node: """ ).strip().lower() _lowerCAmelCase =queue.Queue() _lowerCAmelCase =TreeNode(int(lowercase__ ) ) q.put(lowercase__ ) while not q.empty(): _lowerCAmelCase =q.get() _lowerCAmelCase =f"Enter the left node of {node_found.data}: " _lowerCAmelCase =input(lowercase__ ).strip().lower() or """n""" if check == "n": return tree_node _lowerCAmelCase =TreeNode(int(lowercase__ ) ) _lowerCAmelCase =left_node q.put(lowercase__ ) _lowerCAmelCase =f"Enter the right node of {node_found.data}: " _lowerCAmelCase =input(lowercase__ ).strip().lower() or """n""" if check == "n": return tree_node _lowerCAmelCase =TreeNode(int(lowercase__ ) ) _lowerCAmelCase =right_node q.put(lowercase__ ) raise def snake_case_ ( lowercase__ : TreeNode ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def snake_case_ ( lowercase__ : TreeNode ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def snake_case_ ( lowercase__ : TreeNode ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def snake_case_ ( lowercase__ : TreeNode ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or not node: return _lowerCAmelCase =queue.Queue() q.put(lowercase__ ) while not q.empty(): _lowerCAmelCase =q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def snake_case_ ( lowercase__ : TreeNode ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or not node: return _lowerCAmelCase =queue.Queue() q.put(lowercase__ ) while not q.empty(): _lowerCAmelCase =[] while not q.empty(): _lowerCAmelCase =q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(lowercase__ ) def snake_case_ ( lowercase__ : TreeNode ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or not node: return _lowerCAmelCase =[] _lowerCAmelCase =node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(lowercase__ ) _lowerCAmelCase =n.left # end of while means current node doesn't have left child _lowerCAmelCase =stack.pop() # start to traverse its right child _lowerCAmelCase =n.right def snake_case_ ( lowercase__ : TreeNode ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or not node: return _lowerCAmelCase =[] _lowerCAmelCase =node while n or stack: while n: stack.append(lowercase__ ) _lowerCAmelCase =n.left _lowerCAmelCase =stack.pop() print(n.data , end=""",""" ) _lowerCAmelCase =n.right def snake_case_ ( lowercase__ : TreeNode ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ) or not node: return _lowerCAmelCase , _lowerCAmelCase =[], [] _lowerCAmelCase =node stacka.append(lowercase__ ) while stacka: # to find the reversed order of post order, store it in stack2 _lowerCAmelCase =stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(lowercase__ ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def snake_case_ ( lowercase__ : str = "" , lowercase__ : List[str]=50 , lowercase__ : int="*" ): '''simple docstring''' if not s: return "\n" + width * char _lowerCAmelCase , _lowerCAmelCase =divmod(width - len(lowercase__ ) - 2 , 2 ) return f"{left * char} {s} {(left + extra) * char}" if __name__ == "__main__": import doctest doctest.testmod() print(prompt('''Binary Tree Traversals''')) __SCREAMING_SNAKE_CASE : TreeNode = build_tree() print(prompt('''Pre Order Traversal''')) pre_order(node) print(prompt() + '''\n''') print(prompt('''In Order Traversal''')) in_order(node) print(prompt() + '''\n''') print(prompt('''Post Order Traversal''')) post_order(node) print(prompt() + '''\n''') print(prompt('''Level Order Traversal''')) level_order(node) print(prompt() + '''\n''') print(prompt('''Actual Level Order Traversal''')) level_order_actual(node) print('''*''' * 50 + '''\n''') print(prompt('''Pre Order Traversal - Iteration Version''')) pre_order_iter(node) print(prompt() + '''\n''') print(prompt('''In Order Traversal - Iteration Version''')) in_order_iter(node) print(prompt() + '''\n''') print(prompt('''Post Order Traversal - Iteration Version''')) post_order_iter(node) print(prompt())
712
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE : Optional[int] = logging.get_logger(__name__) # TODO Update this __SCREAMING_SNAKE_CASE : int = { '''facebook/esm-1b''': '''https://huggingface.co/facebook/esm-1b/resolve/main/config.json''', # See all ESM models at https://huggingface.co/models?filter=esm } class __lowerCamelCase ( lowerCamelCase_ ): """simple docstring""" a_: Any = """esm""" def __init__( self : Dict , lowerCamelCase_ : Any=None , lowerCamelCase_ : List[Any]=None , lowerCamelCase_ : Dict=None , lowerCamelCase_ : Tuple=768 , lowerCamelCase_ : List[str]=12 , lowerCamelCase_ : List[Any]=12 , lowerCamelCase_ : Optional[Any]=3072 , lowerCamelCase_ : str=0.1 , lowerCamelCase_ : int=0.1 , lowerCamelCase_ : List[Any]=1026 , lowerCamelCase_ : List[str]=0.02 , lowerCamelCase_ : str=1e-12 , lowerCamelCase_ : int="absolute" , lowerCamelCase_ : Dict=True , lowerCamelCase_ : Optional[int]=None , lowerCamelCase_ : Any=False , lowerCamelCase_ : Dict=False , lowerCamelCase_ : Any=None , lowerCamelCase_ : Union[str, Any]=None , **lowerCamelCase_ : Union[str, Any] , ): super().__init__(pad_token_id=lowerCamelCase_ , mask_token_id=lowerCamelCase_ , **lowerCamelCase_ ) _lowerCAmelCase =vocab_size _lowerCAmelCase =hidden_size _lowerCAmelCase =num_hidden_layers _lowerCAmelCase =num_attention_heads _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 =use_cache _lowerCAmelCase =emb_layer_norm_before _lowerCAmelCase =token_dropout _lowerCAmelCase =is_folding_model if is_folding_model: if esmfold_config is None: logger.info("""No esmfold_config supplied for folding model, using default values.""" ) _lowerCAmelCase =EsmFoldConfig() elif isinstance(lowerCamelCase_ , lowerCamelCase_ ): _lowerCAmelCase =EsmFoldConfig(**lowerCamelCase_ ) _lowerCAmelCase =esmfold_config if vocab_list is None: logger.warning("""No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!""" ) _lowerCAmelCase =get_default_vocab_list() else: _lowerCAmelCase =vocab_list else: _lowerCAmelCase =None _lowerCAmelCase =None if self.esmfold_config is not None and getattr(self.esmfold_config , """use_esm_attn_map""" , lowerCamelCase_ ): raise ValueError("""The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!""" ) def lowerCAmelCase__ ( self : Tuple ): _lowerCAmelCase =super().to_dict() if isinstance(self.esmfold_config , lowerCamelCase_ ): _lowerCAmelCase =self.esmfold_config.to_dict() return output @dataclass class __lowerCamelCase : """simple docstring""" a_: str = None a_: bool = True a_: bool = False a_: bool = False a_: bool = False a_: float = 0 a_: bool = True a_: bool = False a_: int = 1_28 a_: "TrunkConfig" = None def lowerCAmelCase__ ( self : str ): if self.trunk is None: _lowerCAmelCase =TrunkConfig() elif isinstance(self.trunk , lowerCamelCase_ ): _lowerCAmelCase =TrunkConfig(**self.trunk ) def lowerCAmelCase__ ( self : str ): _lowerCAmelCase =asdict(self ) _lowerCAmelCase =self.trunk.to_dict() return output @dataclass class __lowerCamelCase : """simple docstring""" a_: int = 48 a_: int = 10_24 a_: int = 1_28 a_: int = 32 a_: int = 32 a_: int = 32 a_: float = 0 a_: float = 0 a_: bool = False a_: int = 4 a_: Optional[int] = 1_28 a_: "StructureModuleConfig" = None def lowerCAmelCase__ ( self : Optional[Any] ): if self.structure_module is None: _lowerCAmelCase =StructureModuleConfig() elif isinstance(self.structure_module , lowerCamelCase_ ): _lowerCAmelCase =StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(F"`max_recycles` should be positive, got {self.max_recycles}." ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( """`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got""" F" {self.sequence_state_dim} and {self.sequence_state_dim}." ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( """`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got""" F" {self.pairwise_state_dim} and {self.pairwise_state_dim}." ) _lowerCAmelCase =self.sequence_state_dim // self.sequence_head_width _lowerCAmelCase =self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( """`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got""" F" {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}." ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( """`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got""" F" {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}." ) if self.pairwise_state_dim % 2 != 0: raise ValueError(F"`pairwise_state_dim` should be even, got {self.pairwise_state_dim}." ) if self.dropout >= 0.4: raise ValueError(F"`dropout` should not be greater than 0.4, got {self.dropout}." ) def lowerCAmelCase__ ( self : Any ): _lowerCAmelCase =asdict(self ) _lowerCAmelCase =self.structure_module.to_dict() return output @dataclass class __lowerCamelCase : """simple docstring""" a_: int = 3_84 a_: int = 1_28 a_: int = 16 a_: int = 1_28 a_: int = 12 a_: int = 4 a_: int = 8 a_: float = 0.1 a_: int = 8 a_: int = 1 a_: int = 2 a_: int = 7 a_: int = 10 a_: float = 1e-8 a_: float = 1e5 def lowerCAmelCase__ ( self : int ): return asdict(self ) def snake_case_ ( ): '''simple docstring''' return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
149
0
"""simple docstring""" import argparse from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt if __name__ == "__main__": a = argparse.ArgumentParser() parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument( '--original_config_file', type=str, required=True, help='The YAML config file corresponding to the original architecture.', ) parser.add_argument( '--num_in_channels', default=None, type=int, help='The number of input channels. If `None` number of input channels will be automatically inferred.', ) parser.add_argument( '--image_size', default=5_1_2, type=int, help=( 'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2' ' Base. Use 768 for Stable Diffusion v2.' ), ) parser.add_argument( '--extract_ema', action='store_true', help=( 'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights' ' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield' ' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.' ), ) parser.add_argument( '--upcast_attention', action='store_true', help=( 'Whether the attention computation should always be upcasted. This is necessary when running stable' ' diffusion 2.1.' ), ) parser.add_argument( '--from_safetensors', action='store_true', help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.', ) parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') def lowercase (snake_case__ : Tuple ) -> List[str]: '''simple docstring''' if string == "True": return True elif string == "False": return False else: raise ValueError(f'''could not parse string as bool {string}''' ) parser.add_argument( '--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool ) parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int) a = parser.parse_args() a = download_controlnet_from_original_ckpt( checkpoint_path=args.checkpoint_path, original_config_file=args.original_config_file, image_size=args.image_size, extract_ema=args.extract_ema, num_in_channels=args.num_in_channels, upcast_attention=args.upcast_attention, from_safetensors=args.from_safetensors, device=args.device, use_linear_projection=args.use_linear_projection, cross_attention_dim=args.cross_attention_dim, ) controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
169
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin __magic_name__ =get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right __magic_name__ =250004 __magic_name__ =250020 @require_sentencepiece @require_tokenizers class _A ( __UpperCamelCase , unittest.TestCase ): SCREAMING_SNAKE_CASE_ : Any =MBartTokenizer SCREAMING_SNAKE_CASE_ : Any =MBartTokenizerFast SCREAMING_SNAKE_CASE_ : Optional[int] =True SCREAMING_SNAKE_CASE_ : Optional[Any] =True def _a (self ) -> Optional[Any]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing UpperCamelCase__ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) tokenizer.save_pretrained(self.tmpdirname ) def _a (self ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = MBartTokenizer(SCREAMING_SNAKE_CASE_ , keep_accents=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(SCREAMING_SNAKE_CASE_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCamelCase__ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) UpperCamelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ 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] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) UpperCamelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ) self.assertListEqual( SCREAMING_SNAKE_CASE_ , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def _a (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__ = (self.rust_tokenizer_class, '''hf-internal-testing/tiny-random-mbart''', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): UpperCamelCase__ = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tempfile.mkdtemp() UpperCamelCase__ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) UpperCamelCase__ = tuple(f for f in tokenizer_r_files if '''tokenizer.json''' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way UpperCamelCase__ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=True UpperCamelCase__ = tempfile.mkdtemp() UpperCamelCase__ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Checks everything loads correctly in the same way UpperCamelCase__ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) # Save tokenizer rust, legacy_format=False UpperCamelCase__ = tempfile.mkdtemp() UpperCamelCase__ = tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE_ , legacy_format=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('''tokenizer.json''' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way UpperCamelCase__ = tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE_ ) @require_torch @require_sentencepiece @require_tokenizers class _A ( unittest.TestCase ): SCREAMING_SNAKE_CASE_ : Union[str, Any] ="facebook/mbart-large-en-ro" SCREAMING_SNAKE_CASE_ : Any =[ " 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.", ] SCREAMING_SNAKE_CASE_ : Union[str, Any] =[ "Ş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.", ] SCREAMING_SNAKE_CASE_ : str =[82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2, EN_CODE] @classmethod def _a (cls ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang='''en_XX''' , tgt_lang='''ro_RO''' ) UpperCamelCase__ = 1 return cls def _a (self ) -> Dict: '''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 ) def _a (self ) -> Union[str, Any]: '''simple docstring''' UpperCamelCase__ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) def _a (self ) -> Dict: '''simple docstring''' self.assertIn(SCREAMING_SNAKE_CASE_ , self.tokenizer.all_special_ids ) UpperCamelCase__ = [RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] UpperCamelCase__ = self.tokenizer.decode(SCREAMING_SNAKE_CASE_ , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE_ ) def _a (self ) -> Any: '''simple docstring''' UpperCamelCase__ = ['''this is gunna be a long sentence ''' * 20] assert isinstance(src_text[0] , SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = 10 UpperCamelCase__ = self.tokenizer(SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , SCREAMING_SNAKE_CASE_ ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) def _a (self ) -> Optional[int]: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['''<mask>''', '''ar_AR'''] ) , [25_0026, 25_0001] ) def _a (self ) -> Any: '''simple docstring''' UpperCamelCase__ = tempfile.mkdtemp() UpperCamelCase__ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase__ = MBartTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE_ ) @require_torch def _a (self ) -> List[Any]: '''simple docstring''' UpperCamelCase__ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ) UpperCamelCase__ = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def _a (self ) -> Dict: '''simple docstring''' UpperCamelCase__ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=len(self.expected_src_tokens ) , return_tensors='''pt''' , ) UpperCamelCase__ = shift_tokens_right(batch['''labels'''] , self.tokenizer.pad_token_id ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) UpperCamelCase__ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE_ ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def _a (self ) -> str: '''simple docstring''' UpperCamelCase__ = self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=3 , return_tensors='''pt''' ) UpperCamelCase__ = self.tokenizer( text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , max_length=10 , return_tensors='''pt''' ) UpperCamelCase__ = targets['''input_ids'''] UpperCamelCase__ = shift_tokens_right(SCREAMING_SNAKE_CASE_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def _a (self ) -> Tuple: '''simple docstring''' UpperCamelCase__ = self.tokenizer._build_translation_inputs( '''A test''' , return_tensors='''pt''' , src_lang='''en_XX''' , tgt_lang='''ar_AR''' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE_ ) , { # A, test, EOS, en_XX '''input_ids''': [[62, 3034, 2, 25_0004]], '''attention_mask''': [[1, 1, 1, 1]], # ar_AR '''forced_bos_token_id''': 25_0001, } , )
415
0
import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def UpperCamelCase (lowercase_: Optional[int] , lowercase_: str , lowercase_: Any , lowercase_: List[Any] , lowercase_: Tuple ) -> Any: # load base model A__ : List[str] = StableDiffusionPipeline.from_pretrained(lowercase_ , torch_dtype=torch.floataa ) # load LoRA weight from .safetensors A__ : Dict = load_file(lowercase_ ) A__ : List[Any] = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: A__ : Optional[Any] = key.split(""".""" )[0].split(LORA_PREFIX_TEXT_ENCODER + """_""" )[-1].split("""_""" ) A__ : str = pipeline.text_encoder else: A__ : Any = key.split(""".""" )[0].split(LORA_PREFIX_UNET + """_""" )[-1].split("""_""" ) A__ : Union[str, Any] = pipeline.unet # find the target layer A__ : List[str] = layer_infos.pop(0 ) while len(lowercase_ ) > -1: try: A__ : Optional[Any] = curr_layer.__getattr__(lowercase_ ) if len(lowercase_ ) > 0: A__ : List[str] = layer_infos.pop(0 ) elif len(lowercase_ ) == 0: break except Exception: if len(lowercase_ ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: A__ : Dict = layer_infos.pop(0 ) A__ : str = [] if "lora_down" in key: pair_keys.append(key.replace("""lora_down""" , """lora_up""" ) ) pair_keys.append(lowercase_ ) else: pair_keys.append(lowercase_ ) pair_keys.append(key.replace("""lora_up""" , """lora_down""" ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: A__ : List[str] = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) A__ : Optional[int] = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(lowercase_ , lowercase_ ).unsqueeze(2 ).unsqueeze(3 ) else: A__ : str = state_dict[pair_keys[0]].to(torch.floataa ) A__ : List[Any] = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(lowercase_ , lowercase_ ) # update visited list for item in pair_keys: visited.append(lowercase_ ) return pipeline if __name__ == "__main__": A_ : Dict = argparse.ArgumentParser() parser.add_argument( '--base_model_path', default=None, type=str, required=True, help='Path to the base model in diffusers format.' ) parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--lora_prefix_unet', default='lora_unet', type=str, help='The prefix of UNet weight in safetensors' ) parser.add_argument( '--lora_prefix_text_encoder', default='lora_te', type=str, help='The prefix of text encoder weight in safetensors', ) parser.add_argument('--alpha', default=0.75, type=float, help='The merging ratio in W = W0 + alpha * deltaW') parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.' ) parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') A_ : str = parser.parse_args() A_ : int = args.base_model_path A_ : Any = args.checkpoint_path A_ : Optional[int] = args.dump_path A_ : Dict = args.lora_prefix_unet A_ : Optional[int] = args.lora_prefix_text_encoder A_ : List[str] = args.alpha A_ : int = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) A_ : int = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
64
def UpperCamelCase (lowercase_: str , lowercase_: str ) -> bool: A__ : Union[str, Any] = len(lowercase_ ) A__ : List[Any] = len(lowercase_ ) A__ : List[Any] = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] A__ : str = True for i in range(lowercase_ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: A__ : int = True if a[i].islower(): A__ : Dict = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
64
1