code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) a__ : Tuple = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''MobileViTFeatureExtractor'''] a__ : Union[str, Any] = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[int] = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys a__ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" 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, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = BlipImageProcessor() __SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel" ) __SCREAMING_SNAKE_CASE = BlipProcessor(UpperCAmelCase__ , UpperCAmelCase__ ) processor.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self : str , **UpperCAmelCase__ : List[Any] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ).tokenizer def UpperCAmelCase_ ( self : List[Any] , **UpperCAmelCase__ : Dict ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ).image_processor def UpperCAmelCase_ ( self : List[str] ) -> List[str]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self : str ) -> List[Any]: __SCREAMING_SNAKE_CASE = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(UpperCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=UpperCAmelCase__ , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = BlipProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=UpperCAmelCase__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(UpperCAmelCase__ , return_tensors="np" ) __SCREAMING_SNAKE_CASE = processor(images=UpperCAmelCase__ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase_ ( self : Optional[int] ) -> str: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase_ ( self : Any ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase__ ): processor() def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = BlipProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ["pixel_values", "input_ids", "attention_mask"] )
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" from ..utils import is_flax_available, is_torch_available if is_torch_available(): from .autoencoder_kl import AutoencoderKL from .controlnet import ControlNetModel from .dual_transformer_ad import DualTransformeraDModel from .modeling_utils import ModelMixin from .prior_transformer import PriorTransformer from .ta_film_transformer import TaFilmDecoder from .transformer_ad import TransformeraDModel from .unet_ad import UNetaDModel from .unet_ad import UNetaDModel from .unet_ad_condition import UNetaDConditionModel from .unet_ad_condition import UNetaDConditionModel from .vq_model import VQModel if is_flax_available(): from .controlnet_flax import FlaxControlNetModel from .unet_ad_condition_flax import FlaxUNetaDConditionModel from .vae_flax import FlaxAutoencoderKL
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""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_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple=1_3 , UpperCAmelCase__ : Tuple=7 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : int=9_9 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Any=5 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : Optional[Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : List[str]=5_1_2 , UpperCAmelCase__ : int=1_6 , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : Tuple=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> int: 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 UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> int: __SCREAMING_SNAKE_CASE = DistilBertModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = DistilBertForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_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 UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = DistilBertForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_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 UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = DistilBertForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = DistilBertForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_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 UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> int: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = DistilBertForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Optional[int] = ( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) snake_case__ : Optional[Any] = ( { "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__ : List[str] = True snake_case__ : int = True snake_case__ : Any = True snake_case__ : Optional[int] = True def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = DistilBertModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , dim=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = DistilBertModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_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 __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_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" ) ) __SCREAMING_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 UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = DistilBertModel.from_pretrained("distilbert-base-uncased" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 1_1, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_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 ) )
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json''', '''google/bigbird-roberta-large''': '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json''', '''google/bigbird-base-trivia-itc''': '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json''', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Dict = "big_bird" def __init__( self : int , UpperCAmelCase__ : List[str]=5_0_3_5_8 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[Any]=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : List[str]="gelu_new" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : Optional[int]=4_0_9_6 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : Dict=1E-12 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[Any]=0 , UpperCAmelCase__ : Optional[int]=1 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : Optional[Any]=6_6 , UpperCAmelCase__ : List[str]="block_sparse" , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Optional[int]=6_4 , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : str , ) -> Dict: super().__init__( pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , sep_token_id=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = rescale_embeddings __SCREAMING_SNAKE_CASE = attention_type __SCREAMING_SNAKE_CASE = use_bias __SCREAMING_SNAKE_CASE = block_size __SCREAMING_SNAKE_CASE = num_random_blocks __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, 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) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ ) 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(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * num_epochs) , ) # 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" import numpy as np def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return 1 / (1 + np.exp(-vector )) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return vector * sigmoid(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" 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__ : int = logging.get_logger(__name__) a__ : Dict = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''} a__ : Dict = { '''vocab_file''': { '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json''', '''allenai/longformer-large-4096''': ( '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json''' ), '''allenai/longformer-large-4096-finetuned-triviaqa''': ( '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json''' ), '''allenai/longformer-base-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json''' ), '''allenai/longformer-large-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json''' ), }, '''merges_file''': { '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt''', '''allenai/longformer-large-4096''': ( '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt''' ), '''allenai/longformer-large-4096-finetuned-triviaqa''': ( '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt''' ), '''allenai/longformer-base-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt''' ), '''allenai/longformer-large-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt''' ), }, } a__ : List[Any] = { '''allenai/longformer-base-4096''': 4_0_9_6, '''allenai/longformer-large-4096''': 4_0_9_6, '''allenai/longformer-large-4096-finetuned-triviaqa''': 4_0_9_6, '''allenai/longformer-base-4096-extra.pos.embd.only''': 4_0_9_6, '''allenai/longformer-large-4096-extra.pos.embd.only''': 4_0_9_6, } @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = ( list(range(ord("!" ) , ord("~" ) + 1 ) ) + list(range(ord("¡" ) , ord("¬" ) + 1 ) ) + list(range(ord("®" ) , ord("ÿ" ) + 1 ) ) ) __SCREAMING_SNAKE_CASE = bs[:] __SCREAMING_SNAKE_CASE = 0 for b in range(2**8 ): if b not in bs: bs.append(lowerCAmelCase_ ) cs.append(2**8 + n ) n += 1 __SCREAMING_SNAKE_CASE = [chr(lowerCAmelCase_ ) for n in cs] return dict(zip(lowerCAmelCase_ , lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = set() __SCREAMING_SNAKE_CASE = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __SCREAMING_SNAKE_CASE = char return pairs class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] = VOCAB_FILES_NAMES snake_case__ : Tuple = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : int = ["input_ids", "attention_mask"] def __init__( self : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict="replace" , UpperCAmelCase__ : Tuple="<s>" , UpperCAmelCase__ : Optional[Any]="</s>" , UpperCAmelCase__ : Optional[int]="</s>" , UpperCAmelCase__ : Optional[int]="<s>" , UpperCAmelCase__ : Optional[int]="<unk>" , UpperCAmelCase__ : Any="<pad>" , UpperCAmelCase__ : Optional[int]="<mask>" , UpperCAmelCase__ : Union[str, Any]=False , **UpperCAmelCase__ : List[Any] , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else bos_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else eos_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else sep_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else cls_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else unk_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token super().__init__( errors=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , **UpperCAmelCase__ , ) with open(UpperCAmelCase__ , encoding="utf-8" ) as vocab_handle: __SCREAMING_SNAKE_CASE = json.load(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} __SCREAMING_SNAKE_CASE = errors # how to handle errors in decoding __SCREAMING_SNAKE_CASE = bytes_to_unicode() __SCREAMING_SNAKE_CASE = {v: k for k, v in self.byte_encoder.items()} with open(UpperCAmelCase__ , encoding="utf-8" ) as merges_handle: __SCREAMING_SNAKE_CASE = merges_handle.read().split("\n" )[1:-1] __SCREAMING_SNAKE_CASE = [tuple(merge.split() ) for merge in bpe_merges] __SCREAMING_SNAKE_CASE = dict(zip(UpperCAmelCase__ , range(len(UpperCAmelCase__ ) ) ) ) __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions __SCREAMING_SNAKE_CASE = 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 : Optional[Any] ) -> List[str]: return len(self.encoder ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: if token in self.cache: return self.cache[token] __SCREAMING_SNAKE_CASE = tuple(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = get_pairs(UpperCAmelCase__ ) if not pairs: return token while True: __SCREAMING_SNAKE_CASE = min(UpperCAmelCase__ , key=lambda UpperCAmelCase__ : self.bpe_ranks.get(UpperCAmelCase__ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = bigram __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 0 while i < len(UpperCAmelCase__ ): try: __SCREAMING_SNAKE_CASE = word.index(UpperCAmelCase__ , UpperCAmelCase__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __SCREAMING_SNAKE_CASE = j if word[i] == first and i < len(UpperCAmelCase__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __SCREAMING_SNAKE_CASE = tuple(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = new_word if len(UpperCAmelCase__ ) == 1: break else: __SCREAMING_SNAKE_CASE = get_pairs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = " ".join(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = word return word def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> List[str]: __SCREAMING_SNAKE_CASE = [] for token in re.findall(self.pat , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = "".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(UpperCAmelCase__ ).split(" " ) ) return bpe_tokens def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> List[str]: return self.encoder.get(UpperCAmelCase__ , self.encoder.get(self.unk_token ) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[str] ) -> Dict: return self.decoder.get(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = bytearray([self.byte_decoder[c] for c in text] ).decode("utf-8" , errors=self.errors ) return text def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCAmelCase__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __SCREAMING_SNAKE_CASE = os.path.join( UpperCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join( UpperCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(UpperCAmelCase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) + "\n" ) __SCREAMING_SNAKE_CASE = 0 with open(UpperCAmelCase__ , "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 UpperCAmelCase__ : 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!" ) __SCREAMING_SNAKE_CASE = token_index writer.write(" ".join(UpperCAmelCase__ ) + "\n" ) index += 1 return vocab_file, merge_file def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] __SCREAMING_SNAKE_CASE = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None , UpperCAmelCase__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase__ , token_ids_a=UpperCAmelCase__ , already_has_special_tokens=UpperCAmelCase__ ) if token_ids_a is None: return [1] + ([0] * len(UpperCAmelCase__ )) + [1] return [1] + ([0] * len(UpperCAmelCase__ )) + [1, 1] + ([0] * len(UpperCAmelCase__ )) + [1] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [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 : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str=False , **UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = kwargs.pop("add_prefix_space" , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(UpperCAmelCase__ ) > 0 and not text[0].isspace()): __SCREAMING_SNAKE_CASE = " " + text return (text, kwargs)
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin a__ : Tuple = random.Random() if is_torch_available(): import torch def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_=1.0 , lowerCAmelCase_=None , lowerCAmelCase_=None ): '''simple docstring''' if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any]=7 , UpperCAmelCase__ : List[str]=4_0_0 , UpperCAmelCase__ : Any=2_0_0_0 , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : Optional[int]=0.0 , UpperCAmelCase__ : Dict=1_6_0_0_0 , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : List[Any]=True , ) -> Dict: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : int=False ) -> str: def _flatten(UpperCAmelCase__ : Optional[int] ): return list(itertools.chain(*UpperCAmelCase__ ) ) if equal_length: __SCREAMING_SNAKE_CASE = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(UpperCAmelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = ASTFeatureExtractor def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = ASTFeatureExtractionTester(self ) def UpperCAmelCase_ ( self : int ) -> Any: # Tests that all call wrap to encode_plus and batch_encode_plus __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __SCREAMING_SNAKE_CASE = [np.asarray(UpperCAmelCase__ ) for speech_input in speech_inputs] # Test not batched input __SCREAMING_SNAKE_CASE = feat_extract(speech_inputs[0] , return_tensors="np" ).input_values __SCREAMING_SNAKE_CASE = feat_extract(np_speech_inputs[0] , return_tensors="np" ).input_values self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feat_extract(UpperCAmelCase__ , padding=UpperCAmelCase__ , return_tensors="np" ).input_values __SCREAMING_SNAKE_CASE = feat_extract(UpperCAmelCase__ , padding=UpperCAmelCase__ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] __SCREAMING_SNAKE_CASE = np.asarray(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = feat_extract(UpperCAmelCase__ , return_tensors="np" ).input_values __SCREAMING_SNAKE_CASE = feat_extract(UpperCAmelCase__ , return_tensors="np" ).input_values for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) @require_torch def UpperCAmelCase_ ( self : Dict ) -> Optional[int]: import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(1_0_0 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"input_values": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"input_values": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : str ) -> Union[str, Any]: from datasets import load_dataset __SCREAMING_SNAKE_CASE = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("id" ).select(range(UpperCAmelCase__ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] @require_torch def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple: # fmt: off __SCREAMING_SNAKE_CASE = torch.tensor( [-0.9_894, -1.2_776, -0.9_066, -1.2_776, -0.9_349, -1.2_609, -1.0_386, -1.2_776, -1.1_561, -1.2_776, -1.2_052, -1.2_723, -1.2_190, -1.2_132, -1.2_776, -1.1_133, -1.1_953, -1.1_343, -1.1_584, -1.2_203, -1.1_770, -1.2_474, -1.2_381, -1.1_936, -0.9_270, -0.8_317, -0.8_049, -0.7_706, -0.7_565, -0.7_869] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = ASTFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="pt" ).input_values self.assertEquals(input_values.shape , (1, 1_0_2_4, 1_2_8) ) self.assertTrue(torch.allclose(input_values[0, 0, :3_0] , UpperCAmelCase__ , atol=1E-4 ) )
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a__ : str = { '''configuration_bridgetower''': [ '''BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BridgeTowerConfig''', '''BridgeTowerTextConfig''', '''BridgeTowerVisionConfig''', ], '''processing_bridgetower''': ['''BridgeTowerProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = ['''BridgeTowerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = [ '''BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BridgeTowerForContrastiveLearning''', '''BridgeTowerForImageAndTextRetrieval''', '''BridgeTowerForMaskedLM''', '''BridgeTowerModel''', '''BridgeTowerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys a__ : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def UpperCAmelCase_ ( self : List[Any] ) -> str: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import importlib import os import fsspec import pytest from fsspec import register_implementation from fsspec.registry import _registry as _fsspec_registry from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem from .utils import require_lza, require_zstandard def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' assert "mock" in _fsspec_registry assert "bz2" in _fsspec_registry def UpperCAmelCase__ (): '''simple docstring''' assert "mock" not in _fsspec_registry assert "bz2" in _fsspec_registry def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = "mock-s3-bucket" __SCREAMING_SNAKE_CASE = f"""s3://{mock_bucket}""" __SCREAMING_SNAKE_CASE = extract_path_from_uri(lowerCAmelCase_ ) assert dataset_path.startswith("s3://" ) is False __SCREAMING_SNAKE_CASE = "./local/path" __SCREAMING_SNAKE_CASE = extract_path_from_uri(lowerCAmelCase_ ) assert dataset_path == new_dataset_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = is_remote_filesystem(lowerCAmelCase_ ) assert is_remote is True __SCREAMING_SNAKE_CASE = fsspec.filesystem("file" ) __SCREAMING_SNAKE_CASE = is_remote_filesystem(lowerCAmelCase_ ) assert is_remote is False @pytest.mark.parametrize("compression_fs_class" , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bza_file, "lz4": lza_file} __SCREAMING_SNAKE_CASE = input_paths[compression_fs_class.protocol] if input_path is None: __SCREAMING_SNAKE_CASE = f"""for '{compression_fs_class.protocol}' compression protocol, """ if compression_fs_class.protocol == "lz4": reason += require_lza.kwargs["reason"] elif compression_fs_class.protocol == "zstd": reason += require_zstandard.kwargs["reason"] pytest.skip(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fsspec.filesystem(compression_fs_class.protocol , fo=lowerCAmelCase_ ) assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = os.path.basename(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = expected_filename[: expected_filename.rindex("." )] assert fs.glob("*" ) == [expected_filename] with fs.open(lowerCAmelCase_ , "r" , encoding="utf-8" ) as f, open(lowerCAmelCase_ , encoding="utf-8" ) as expected_file: assert f.read() == expected_file.read() @pytest.mark.parametrize("protocol" , ["zip", "gzip"] ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {"zip": zip_jsonl_path, "gzip": jsonl_gz_path} __SCREAMING_SNAKE_CASE = compressed_file_paths[protocol] __SCREAMING_SNAKE_CASE = "dataset.jsonl" __SCREAMING_SNAKE_CASE = f"""{protocol}://{member_file_path}::{compressed_file_path}""" __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE = fsspec.get_fs_token_paths(lowerCAmelCase_ ) assert fs.isfile(lowerCAmelCase_ ) assert not fs.isfile("non_existing_" + member_file_path ) @pytest.mark.integration def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = hf_api.dataset_info(lowerCAmelCase_ , token=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = HfFileSystem(repo_info=lowerCAmelCase_ , token=lowerCAmelCase_ ) assert sorted(hffs.glob("*" ) ) == [".gitattributes", "data"] assert hffs.isdir("data" ) assert hffs.isfile(".gitattributes" ) and hffs.isfile("data/text_data.txt" ) with open(lowerCAmelCase_ ) as f: assert hffs.open("data/text_data.txt" , "r" ).read() == f.read() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = "bz2" # Import module import datasets.filesystems # Overwrite protocol and reload register_implementation(lowerCAmelCase_ , lowerCAmelCase_ , clobber=lowerCAmelCase_ ) with pytest.warns(lowerCAmelCase_ ) as warning_info: importlib.reload(datasets.filesystems ) assert len(lowerCAmelCase_ ) == 1 assert ( str(warning_info[0].message ) == f"""A filesystem protocol was already set for {protocol} and will be overwritten.""" )
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a__ : List[Any] = logging.get_logger(__name__) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.getenv("SM_HP_MP_PARAMETERS" , "{}" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. __SCREAMING_SNAKE_CASE = os.getenv("SM_FRAMEWORK_PARAMS" , "{}" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". __SCREAMING_SNAKE_CASE = json.loads(lowerCAmelCase_ ) if not mpi_options.get("sagemaker_mpi_enabled" , lowerCAmelCase_ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("smdistributed" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: super().__post_init__() warnings.warn( "`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use " "`TrainingArguments` instead." , UpperCAmelCase__ , ) @cached_property def UpperCAmelCase_ ( self : Dict ) -> "torch.device": logger.info("PyTorch: setting up devices" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( "torch.distributed process group is initialized, but local_rank == -1. " "In order to use Torch DDP, launch your script with `python -m torch.distributed.launch" ) if self.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cpu" ) __SCREAMING_SNAKE_CASE = 0 elif is_sagemaker_model_parallel_available(): __SCREAMING_SNAKE_CASE = smp.local_rank() __SCREAMING_SNAKE_CASE = torch.device("cuda" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="smddp" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = int(os.getenv("SMDATAPARALLEL_LOCAL_RANK" ) ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. __SCREAMING_SNAKE_CASE = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="nccl" , timeout=self.ddp_timeout_delta ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , self.local_rank ) __SCREAMING_SNAKE_CASE = 1 if device.type == "cuda": torch.cuda.set_device(UpperCAmelCase__ ) return device @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: return not is_sagemaker_model_parallel_available() @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> Dict: return False
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" @register_to_config def __init__( self : Dict , *, UpperCAmelCase__ : int = 4 , UpperCAmelCase__ : int = 7_6_8 , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> Union[str, Any]: super().__init__() __SCREAMING_SNAKE_CASE = nn.Parameter(torch.zeros(UpperCAmelCase__ ) ) # parameters for additional clip time embeddings __SCREAMING_SNAKE_CASE = nn.Linear(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = nn.Linear(UpperCAmelCase__ , UpperCAmelCase__ ) # parameters for encoder hidden states __SCREAMING_SNAKE_CASE = clip_extra_context_tokens __SCREAMING_SNAKE_CASE = nn.Linear( UpperCAmelCase__ , self.clip_extra_context_tokens * cross_attention_dim ) __SCREAMING_SNAKE_CASE = nn.Linear(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = nn.LayerNorm(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] , *, UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Any ) -> Union[str, Any]: if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings __SCREAMING_SNAKE_CASE = image_embeddings.shape[0] __SCREAMING_SNAKE_CASE = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) __SCREAMING_SNAKE_CASE = classifier_free_guidance_embeddings.expand( UpperCAmelCase__ , -1 ) __SCREAMING_SNAKE_CASE = 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] __SCREAMING_SNAKE_CASE = 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, ... __SCREAMING_SNAKE_CASE = self.embedding_proj(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.clip_image_embeddings_project_to_time_embeddings(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 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" __SCREAMING_SNAKE_CASE = self.clip_extra_context_tokens_proj(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = clip_extra_context_tokens.reshape(UpperCAmelCase__ , -1 , self.clip_extra_context_tokens ) __SCREAMING_SNAKE_CASE = clip_extra_context_tokens.permute(0 , 2 , 1 ) __SCREAMING_SNAKE_CASE = self.encoder_hidden_states_proj(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.text_encoder_hidden_states_norm(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : List[Any] ) -> Union[str, Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result["bs"] , model_result["ss"] ): __SCREAMING_SNAKE_CASE = model_result["result"][batch_size][sequence_length] self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=UpperCAmelCase__ , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "sgugger/tiny-distilbert-classification" __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase__ , only_pretrain_model=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=UpperCAmelCase__ , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ , [config] ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase_ ( self : str ) -> List[Any]: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ , [config] ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase_ ( self : List[str] ) -> str: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ , [config] ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase_ ( self : Dict ) -> str: __SCREAMING_SNAKE_CASE = "patrickvonplaten/t5-tiny-random" __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ , configs=[config] ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices("GPU" ) ) == 0 , "Cannot do xla on CPU." ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase__ , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , use_xla=UpperCAmelCase__ , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" with tempfile.TemporaryDirectory() as tmp_dir: __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=UpperCAmelCase__ , save_to_csv=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(UpperCAmelCase__ , "inf_time.csv" ) , inference_memory_csv_file=os.path.join(UpperCAmelCase__ , "inf_mem.csv" ) , env_info_csv_file=os.path.join(UpperCAmelCase__ , "env.csv" ) , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ ) benchmark.run() self.assertTrue(Path(os.path.join(UpperCAmelCase__ , "inf_time.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCAmelCase__ , "inf_mem.csv" ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCAmelCase__ , "env.csv" ) ).exists() ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = "sshleifer/tiny-gpt2" def _check_summary_is_not_empty(UpperCAmelCase__ : List[str] ): self.assertTrue(hasattr(UpperCAmelCase__ , "sequential" ) ) self.assertTrue(hasattr(UpperCAmelCase__ , "cumulative" ) ) self.assertTrue(hasattr(UpperCAmelCase__ , "current" ) ) self.assertTrue(hasattr(UpperCAmelCase__ , "total" ) ) with tempfile.TemporaryDirectory() as tmp_dir: __SCREAMING_SNAKE_CASE = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=UpperCAmelCase__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(UpperCAmelCase__ , "log.txt" ) , log_print=UpperCAmelCase__ , trace_memory_line_by_line=UpperCAmelCase__ , eager_mode=UpperCAmelCase__ , multi_process=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = TensorFlowBenchmark(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(UpperCAmelCase__ , "log.txt" ) ).exists() )
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Optional[Any] = VideoToVideoSDPipeline snake_case__ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"}) - {"image", "width", "height"} snake_case__ : Dict = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"}) - {"image"} snake_case__ : List[str] = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ : str = False # No `output_type`. snake_case__ : Optional[Any] = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ]) def UpperCAmelCase_ ( self : str ) -> Tuple: torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(3_2, 6_4, 6_4, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=3_2 , attention_head_dim=4 , ) __SCREAMING_SNAKE_CASE = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase__ , set_alpha_to_one=UpperCAmelCase__ , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=1_2_8 , ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , hidden_act="gelu" , projection_dim=5_1_2 , ) __SCREAMING_SNAKE_CASE = CLIPTextModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __SCREAMING_SNAKE_CASE = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any]=0 ) -> int: # 3 frames __SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 3, 3_2, 3_2) , rng=random.Random(UpperCAmelCase__ ) ).to(UpperCAmelCase__ ) if str(UpperCAmelCase__ ).startswith("mps" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = VideoToVideoSDPipeline(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "np" __SCREAMING_SNAKE_CASE = sd_pipe(**UpperCAmelCase__ ).frames __SCREAMING_SNAKE_CASE = frames[0][-3:, -3:, -1] assert frames[0].shape == (3_2, 3_2, 3) __SCREAMING_SNAKE_CASE = np.array([1_0_6, 1_1_7, 1_1_3, 1_7_4, 1_3_7, 1_1_2, 1_4_8, 1_5_1, 1_3_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def UpperCAmelCase_ ( self : str ) -> Optional[Any]: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=UpperCAmelCase__ , expected_max_diff=5E-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def UpperCAmelCase_ ( self : str ) -> int: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: pass def UpperCAmelCase_ ( self : str ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames __SCREAMING_SNAKE_CASE = torch.Generator(device="cpu" ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn((1, 1_0, 3, 1_0_2_4, 5_7_6) , generator=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = video.to("cuda" ) __SCREAMING_SNAKE_CASE = "Spiderman is surfing" __SCREAMING_SNAKE_CASE = pipe(UpperCAmelCase__ , video=UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=3 , output_type="pt" ).frames __SCREAMING_SNAKE_CASE = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : int = logging.get_logger(__name__) a__ : Any = { '''unc-nlp/lxmert-base-uncased''': '''https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json''', } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "lxmert" snake_case__ : Optional[Any] = {} def __init__( self : Optional[Any] , UpperCAmelCase__ : List[Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[int]=7_6_8 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : Tuple=9_5_0_0 , UpperCAmelCase__ : List[str]=1_6_0_0 , UpperCAmelCase__ : Tuple=4_0_0 , UpperCAmelCase__ : Dict=3_0_7_2 , UpperCAmelCase__ : List[Any]="gelu" , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : str=5_1_2 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : Optional[Any]=1E-12 , UpperCAmelCase__ : Optional[int]=9 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Any=5 , UpperCAmelCase__ : Dict=2_0_4_8 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : List[Any]=6.67 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Any=True , **UpperCAmelCase__ : str , ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = num_qa_labels __SCREAMING_SNAKE_CASE = num_object_labels __SCREAMING_SNAKE_CASE = num_attr_labels __SCREAMING_SNAKE_CASE = l_layers __SCREAMING_SNAKE_CASE = x_layers __SCREAMING_SNAKE_CASE = r_layers __SCREAMING_SNAKE_CASE = visual_feat_dim __SCREAMING_SNAKE_CASE = visual_pos_dim __SCREAMING_SNAKE_CASE = visual_loss_normalizer __SCREAMING_SNAKE_CASE = task_matched __SCREAMING_SNAKE_CASE = task_mask_lm __SCREAMING_SNAKE_CASE = task_obj_predict __SCREAMING_SNAKE_CASE = task_qa __SCREAMING_SNAKE_CASE = visual_obj_loss __SCREAMING_SNAKE_CASE = visual_attr_loss __SCREAMING_SNAKE_CASE = visual_feat_loss __SCREAMING_SNAKE_CASE = {"vision": r_layers, "cross_encoder": x_layers, "language": l_layers} super().__init__(**UpperCAmelCase__ )
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) 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 UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=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 UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_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__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.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 UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="attention" ): '''simple docstring''' __SCREAMING_SNAKE_CASE = params[f"""{prefix}/layers_{i}/{layer_name}/key/kernel"""] __SCREAMING_SNAKE_CASE = params[f"""{prefix}/layers_{i}/{layer_name}/out/kernel"""] __SCREAMING_SNAKE_CASE = params[f"""{prefix}/layers_{i}/{layer_name}/query/kernel"""] __SCREAMING_SNAKE_CASE = params[f"""{prefix}/layers_{i}/{layer_name}/value/kernel"""] return k, o, q, v def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False ): '''simple docstring''' if split_mlp_wi: __SCREAMING_SNAKE_CASE = params[f"""{prefix}/layers_{i}/mlp/wi_0/kernel"""] __SCREAMING_SNAKE_CASE = params[f"""{prefix}/layers_{i}/mlp/wi_1/kernel"""] __SCREAMING_SNAKE_CASE = (wi_a, wi_a) else: __SCREAMING_SNAKE_CASE = params[f"""{prefix}/layers_{i}/mlp/wi/kernel"""] __SCREAMING_SNAKE_CASE = params[f"""{prefix}/layers_{i}/mlp/wo/kernel"""] return wi, wo def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return params[f"""{prefix}/layers_{i}/{layer_name}/scale"""] def UpperCAmelCase__ (lowerCAmelCase_ , *, lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = traverse_util.flatten_dict(variables["target"] ) __SCREAMING_SNAKE_CASE = {"/".join(lowerCAmelCase_ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi __SCREAMING_SNAKE_CASE = "encoder/layers_0/mlp/wi_0/kernel" in old print("Split MLP:" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = collections.OrderedDict() # Shared embeddings. __SCREAMING_SNAKE_CASE = old["token_embedder/embedding"] # Encoder. for i in range(lowerCAmelCase_ ): # Block i, layer 0 (Self Attention). __SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "encoder" , "pre_attention_layer_norm" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tax_attention_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "encoder" , "attention" ) __SCREAMING_SNAKE_CASE = layer_norm __SCREAMING_SNAKE_CASE = k.T __SCREAMING_SNAKE_CASE = o.T __SCREAMING_SNAKE_CASE = q.T __SCREAMING_SNAKE_CASE = v.T # Block i, layer 1 (MLP). __SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "encoder" , "pre_mlp_layer_norm" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tax_mlp_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "encoder" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = layer_norm if split_mlp_wi: __SCREAMING_SNAKE_CASE = wi[0].T __SCREAMING_SNAKE_CASE = wi[1].T else: __SCREAMING_SNAKE_CASE = wi.T __SCREAMING_SNAKE_CASE = wo.T __SCREAMING_SNAKE_CASE = old[ "encoder/relpos_bias/rel_embedding" ].T __SCREAMING_SNAKE_CASE = old["encoder/encoder_norm/scale"] if not is_encoder_only: # Decoder. for i in range(lowerCAmelCase_ ): # Block i, layer 0 (Self Attention). __SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "decoder" , "pre_self_attention_layer_norm" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tax_attention_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "decoder" , "self_attention" ) __SCREAMING_SNAKE_CASE = layer_norm __SCREAMING_SNAKE_CASE = k.T __SCREAMING_SNAKE_CASE = o.T __SCREAMING_SNAKE_CASE = q.T __SCREAMING_SNAKE_CASE = v.T # Block i, layer 1 (Cross Attention). __SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "decoder" , "pre_cross_attention_layer_norm" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tax_attention_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "decoder" , "encoder_decoder_attention" ) __SCREAMING_SNAKE_CASE = layer_norm __SCREAMING_SNAKE_CASE = k.T __SCREAMING_SNAKE_CASE = o.T __SCREAMING_SNAKE_CASE = q.T __SCREAMING_SNAKE_CASE = v.T # Block i, layer 2 (MLP). __SCREAMING_SNAKE_CASE = tax_layer_norm_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "decoder" , "pre_mlp_layer_norm" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tax_mlp_lookup(lowerCAmelCase_ , lowerCAmelCase_ , "decoder" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = layer_norm if split_mlp_wi: __SCREAMING_SNAKE_CASE = wi[0].T __SCREAMING_SNAKE_CASE = wi[1].T else: __SCREAMING_SNAKE_CASE = wi.T __SCREAMING_SNAKE_CASE = wo.T __SCREAMING_SNAKE_CASE = old["decoder/decoder_norm/scale"] __SCREAMING_SNAKE_CASE = old[ "decoder/relpos_bias/rel_embedding" ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: __SCREAMING_SNAKE_CASE = old["decoder/logits_dense/kernel"].T return new def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: __SCREAMING_SNAKE_CASE = state_dict["shared.weight"] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: __SCREAMING_SNAKE_CASE = state_dict["shared.weight"] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("Using shared word embeddings as lm_head." ) __SCREAMING_SNAKE_CASE = state_dict["shared.weight"] return state_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = convert_tax_to_pytorch(lowerCAmelCase_ , num_layers=config.num_layers , is_encoder_only=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = make_state_dict(lowerCAmelCase_ , lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = TaConfig.from_json_file(lowerCAmelCase_ ) print(f"""Building PyTorch model from configuration: {config}""" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: __SCREAMING_SNAKE_CASE = TaEncoderModel(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = TaForConditionalGeneration(lowerCAmelCase_ ) # Load weights from tf checkpoint load_tax_weights_in_ta(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) model.save_pretrained(lowerCAmelCase_ ) # Verify that we can load the checkpoint. model.from_pretrained(lowerCAmelCase_ ) print("Done" ) if __name__ == "__main__": a__ : str = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) a__ : Any = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" import 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 a__ : Union[str, Any] = ['''bart.large''', '''bart.large.mnli''', '''bart.large.cnn''', '''bart_xsum/model.pt'''] a__ : Any = {'''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() a__ : Optional[Any] = logging.get_logger(__name__) a__ : List[Any] = ''' Hello world! cécé herlolip''' a__ : Any = [ ('''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 UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "_float_tensor", ] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = dct.pop(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = val def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location="cpu" ) __SCREAMING_SNAKE_CASE = torch.hub.load("pytorch/fairseq" , "bart.large.cnn" ).eval() hub_interface.model.load_state_dict(sd["model"] ) return hub_interface def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = emb.weight.shape __SCREAMING_SNAKE_CASE = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ , bias=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None ): '''simple docstring''' if not os.path.exists(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = torch.hub.load("pytorch/fairseq" , lowerCAmelCase_ ).eval() else: __SCREAMING_SNAKE_CASE = load_xsum_checkpoint(lowerCAmelCase_ ) bart.model.upgrade_state_dict(bart.model.state_dict() ) if hf_checkpoint_name is None: __SCREAMING_SNAKE_CASE = checkpoint_path.replace("." , "-" ) __SCREAMING_SNAKE_CASE = BartConfig.from_pretrained(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = bart.encode(lowerCAmelCase_ ).unsqueeze(0 ) __SCREAMING_SNAKE_CASE = BartTokenizer.from_pretrained(lowerCAmelCase_ ).encode(lowerCAmelCase_ , return_tensors="pt" ).unsqueeze(0 ) if not torch.eq(lowerCAmelCase_ , lowerCAmelCase_ ).all(): raise ValueError( f"""converted tokenizer and pretrained tokenizer returned different output: {tokens} != {tokensa}""" ) if checkpoint_path == "bart.large.mnli": __SCREAMING_SNAKE_CASE = bart.state_dict() remove_ignore_keys_(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = state_dict["model.decoder.embed_tokens.weight"] for src, dest in mnli_rename_keys: rename_key(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = BartForSequenceClassification(lowerCAmelCase_ ).eval() model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = bart.predict("mnli" , lowerCAmelCase_ , return_logits=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ )[0] # logits else: # no classification heads to worry about __SCREAMING_SNAKE_CASE = bart.model.state_dict() remove_ignore_keys_(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = state_dict["decoder.embed_tokens.weight"] __SCREAMING_SNAKE_CASE = bart.extract_features(lowerCAmelCase_ ) if hf_checkpoint_name == "facebook/bart-large": __SCREAMING_SNAKE_CASE = BartModel(lowerCAmelCase_ ).eval() model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ ).model[0] else: __SCREAMING_SNAKE_CASE = BartForConditionalGeneration(lowerCAmelCase_ ).eval() # an existing summarization ckpt model.model.load_state_dict(lowerCAmelCase_ ) if hasattr(lowerCAmelCase_ , "lm_head" ): __SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared ) __SCREAMING_SNAKE_CASE = model.model(lowerCAmelCase_ )[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(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": a__ : str = 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''' ) a__ : Union[str, Any] = parser.parse_args() convert_bart_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, hf_checkpoint_name=args.hf_config)
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) a__ : Union[str, Any] = { '''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''], '''processing_trocr''': ['''TrOCRProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[Any] = [ '''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TrOCRForCausalLM''', '''TrOCRPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy 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 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input a__ : Tuple = '''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = _ask_options( "In which compute environment are you running?" , ["This machine", "AWS (Amazon SageMaker)"] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: __SCREAMING_SNAKE_CASE = get_sagemaker_input() else: __SCREAMING_SNAKE_CASE = get_cluster_input() return config def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("config" , description=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate config command" , description=lowerCAmelCase_ ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_user_input() if args.config_file is not None: __SCREAMING_SNAKE_CASE = args.config_file else: if not os.path.isdir(lowerCAmelCase_ ): os.makedirs(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = default_yaml_config_file if config_file.endswith(".json" ): config.to_json_file(lowerCAmelCase_ ) else: config.to_yaml_file(lowerCAmelCase_ ) print(f"""accelerate configuration saved at {config_file}""" ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = config_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() config_command(lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "block_out_channels": [3_2, 6_4], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""simple docstring""" 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, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING a__ : str = logging.get_logger(__name__) a__ : Optional[Any] = Dict[str, Any] a__ : List[Any] = List[Prediction] @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : List[Any] , *UpperCAmelCase__ : Optional[int] , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if self.framework == "tf": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) requires_backends(self , "vision" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def UpperCAmelCase_ ( self : str , **UpperCAmelCase__ : Any ) -> str: __SCREAMING_SNAKE_CASE = {} if "threshold" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["threshold"] return {}, {}, postprocess_kwargs def __call__( self : Union[str, Any] , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : Optional[int] ) -> Union[Predictions, List[Prediction]]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = load_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.IntTensor([[image.height, image.width]] ) __SCREAMING_SNAKE_CASE = self.image_processor(images=[image] , return_tensors="pt" ) if self.tokenizer is not None: __SCREAMING_SNAKE_CASE = self.tokenizer(text=inputs["words"] , boxes=inputs["boxes"] , return_tensors="pt" ) __SCREAMING_SNAKE_CASE = target_size return inputs def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = model_inputs.pop("target_size" ) __SCREAMING_SNAKE_CASE = self.model(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.__class__({"target_size": target_size, **outputs} ) if self.tokenizer is not None: __SCREAMING_SNAKE_CASE = model_inputs["bbox"] return model_outputs def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any]=0.9 ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs["target_size"] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = target_size[0].tolist() def unnormalize(UpperCAmelCase__ : Tuple ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1_0_0_0), (height * bbox[1] / 1_0_0_0), (width * bbox[2] / 1_0_0_0), (height * bbox[3] / 1_0_0_0), ] ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_outputs["logits"].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) __SCREAMING_SNAKE_CASE = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] __SCREAMING_SNAKE_CASE = [unnormalize(UpperCAmelCase__ ) for bbox in model_outputs["bbox"].squeeze(0 )] __SCREAMING_SNAKE_CASE = ["score", "label", "box"] __SCREAMING_SNAKE_CASE = [dict(zip(UpperCAmelCase__ , UpperCAmelCase__ ) ) for vals in zip(scores.tolist() , UpperCAmelCase__ , UpperCAmelCase__ ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel __SCREAMING_SNAKE_CASE = self.image_processor.post_process_object_detection(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = raw_annotations[0] __SCREAMING_SNAKE_CASE = raw_annotation["scores"] __SCREAMING_SNAKE_CASE = raw_annotation["labels"] __SCREAMING_SNAKE_CASE = raw_annotation["boxes"] __SCREAMING_SNAKE_CASE = scores.tolist() __SCREAMING_SNAKE_CASE = [self.model.config.idalabel[label.item()] for label in labels] __SCREAMING_SNAKE_CASE = [self._get_bounding_box(UpperCAmelCase__ ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] __SCREAMING_SNAKE_CASE = ["score", "label", "box"] __SCREAMING_SNAKE_CASE = [ dict(zip(UpperCAmelCase__ , UpperCAmelCase__ ) ) for vals in zip(raw_annotation["scores"] , raw_annotation["labels"] , raw_annotation["boxes"] ) ] return annotation def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : "torch.Tensor" ) -> Dict[str, int]: if self.framework != "pt": raise ValueError("The ObjectDetectionPipeline is only available in PyTorch." ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = box.int().tolist() __SCREAMING_SNAKE_CASE = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() a__ : Dict = logging.get_logger(__name__) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = UniSpeechSatForSequenceClassification.from_pretrained(lowerCAmelCase_ , config=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = downstream_dict["projector.weight"] __SCREAMING_SNAKE_CASE = downstream_dict["projector.bias"] __SCREAMING_SNAKE_CASE = downstream_dict["model.post_net.linear.weight"] __SCREAMING_SNAKE_CASE = downstream_dict["model.post_net.linear.bias"] return model def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = UniSpeechSatForAudioFrameClassification.from_pretrained(lowerCAmelCase_ , config=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = downstream_dict["model.linear.weight"] __SCREAMING_SNAKE_CASE = downstream_dict["model.linear.bias"] return model def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = UniSpeechSatForXVector.from_pretrained(lowerCAmelCase_ , config=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = downstream_dict["connector.weight"] __SCREAMING_SNAKE_CASE = downstream_dict["connector.bias"] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): __SCREAMING_SNAKE_CASE = downstream_dict[ f"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] __SCREAMING_SNAKE_CASE = downstream_dict[f"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] __SCREAMING_SNAKE_CASE = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"] __SCREAMING_SNAKE_CASE = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"] __SCREAMING_SNAKE_CASE = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"] __SCREAMING_SNAKE_CASE = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"] __SCREAMING_SNAKE_CASE = downstream_dict["objective.W"] return model @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location="cpu" ) __SCREAMING_SNAKE_CASE = checkpoint["Downstream"] __SCREAMING_SNAKE_CASE = UniSpeechSatConfig.from_pretrained(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained( lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , do_normalize=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = hf_config.architectures[0] if arch.endswith("ForSequenceClassification" ): __SCREAMING_SNAKE_CASE = convert_classification(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) elif arch.endswith("ForAudioFrameClassification" ): __SCREAMING_SNAKE_CASE = convert_diarization(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) elif arch.endswith("ForXVector" ): __SCREAMING_SNAKE_CASE = convert_xvector(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) else: raise NotImplementedError(f"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: __SCREAMING_SNAKE_CASE = checkpoint["Featurizer"]["weights"] hf_feature_extractor.save_pretrained(lowerCAmelCase_ ) hf_model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": a__ : List[Any] = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') a__ : Optional[int] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging a__ : str = logging.get_logger(__name__) a__ : Optional[int] = '''▁''' a__ : int = { '''vocab_file''': '''vocab.json''', '''spm_file''': '''sentencepiece.bpe.model''', '''tokenizer_config_file''': '''tokenizer_config.json''', } a__ : List[str] = { '''vocab_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json''', }, '''spm_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_config_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json''', }, } a__ : str = { '''facebook/m2m100_418M''': 1_0_2_4, } # fmt: off a__ : str = { '''m2m100''': ['''af''', '''am''', '''ar''', '''ast''', '''az''', '''ba''', '''be''', '''bg''', '''bn''', '''br''', '''bs''', '''ca''', '''ceb''', '''cs''', '''cy''', '''da''', '''de''', '''el''', '''en''', '''es''', '''et''', '''fa''', '''ff''', '''fi''', '''fr''', '''fy''', '''ga''', '''gd''', '''gl''', '''gu''', '''ha''', '''he''', '''hi''', '''hr''', '''ht''', '''hu''', '''hy''', '''id''', '''ig''', '''ilo''', '''is''', '''it''', '''ja''', '''jv''', '''ka''', '''kk''', '''km''', '''kn''', '''ko''', '''lb''', '''lg''', '''ln''', '''lo''', '''lt''', '''lv''', '''mg''', '''mk''', '''ml''', '''mn''', '''mr''', '''ms''', '''my''', '''ne''', '''nl''', '''no''', '''ns''', '''oc''', '''or''', '''pa''', '''pl''', '''ps''', '''pt''', '''ro''', '''ru''', '''sd''', '''si''', '''sk''', '''sl''', '''so''', '''sq''', '''sr''', '''ss''', '''su''', '''sv''', '''sw''', '''ta''', '''th''', '''tl''', '''tn''', '''tr''', '''uk''', '''ur''', '''uz''', '''vi''', '''wo''', '''xh''', '''yi''', '''yo''', '''zh''', '''zu'''], '''wmt21''': ['''en''', '''ha''', '''is''', '''ja''', '''cs''', '''ru''', '''zh''', '''de'''] } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[Any] = VOCAB_FILES_NAMES snake_case__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Any = ["input_ids", "attention_mask"] snake_case__ : List[int] = [] snake_case__ : List[int] = [] def __init__( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any="<s>" , UpperCAmelCase__ : List[str]="</s>" , UpperCAmelCase__ : Optional[int]="</s>" , UpperCAmelCase__ : List[str]="<pad>" , UpperCAmelCase__ : Union[str, Any]="<unk>" , UpperCAmelCase__ : List[str]="m2m100" , UpperCAmelCase__ : Optional[Dict[str, Any]] = None , UpperCAmelCase__ : int=8 , **UpperCAmelCase__ : List[Any] , ) -> None: __SCREAMING_SNAKE_CASE = {} if sp_model_kwargs is None else sp_model_kwargs __SCREAMING_SNAKE_CASE = language_codes __SCREAMING_SNAKE_CASE = FAIRSEQ_LANGUAGE_CODES[language_codes] __SCREAMING_SNAKE_CASE = {lang_code: F"""__{lang_code}__""" for lang_code in fairseq_language_code} __SCREAMING_SNAKE_CASE = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(UpperCAmelCase__ ) for lang_code in fairseq_language_code if self.get_lang_token(UpperCAmelCase__ ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , language_codes=UpperCAmelCase__ , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = vocab_file __SCREAMING_SNAKE_CASE = load_json(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {v: k for k, v in self.encoder.items()} __SCREAMING_SNAKE_CASE = spm_file __SCREAMING_SNAKE_CASE = load_spm(UpperCAmelCase__ , self.sp_model_kwargs ) __SCREAMING_SNAKE_CASE = len(self.encoder ) __SCREAMING_SNAKE_CASE = { self.get_lang_token(UpperCAmelCase__ ): self.encoder_size + i for i, lang_code in enumerate(UpperCAmelCase__ ) } __SCREAMING_SNAKE_CASE = {lang_code: self.encoder_size + i for i, lang_code in enumerate(UpperCAmelCase__ )} __SCREAMING_SNAKE_CASE = {v: k for k, v in self.lang_token_to_id.items()} __SCREAMING_SNAKE_CASE = src_lang if src_lang is not None else "en" __SCREAMING_SNAKE_CASE = tgt_lang __SCREAMING_SNAKE_CASE = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) __SCREAMING_SNAKE_CASE = num_madeup_words @property def UpperCAmelCase_ ( self : Optional[int] ) -> int: return len(self.encoder ) + len(self.lang_token_to_id ) @property def UpperCAmelCase_ ( self : Any ) -> str: return self._src_lang @src_lang.setter def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str ) -> None: __SCREAMING_SNAKE_CASE = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str ) -> List[str]: return self.sp_model.encode(UpperCAmelCase__ , out_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Dict: if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(UpperCAmelCase__ , self.encoder[self.unk_token] ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : int ) -> str: if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(UpperCAmelCase__ , self.unk_token ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : int ) -> Optional[Any]: __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(UpperCAmelCase__ ) + token __SCREAMING_SNAKE_CASE = [] else: current_sub_tokens.append(UpperCAmelCase__ ) out_string += self.sp_model.decode(UpperCAmelCase__ ) return out_string.strip() def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None , UpperCAmelCase__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase__ , token_ids_a=UpperCAmelCase__ , already_has_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [1] * len(self.prefix_tokens ) __SCREAMING_SNAKE_CASE = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(UpperCAmelCase__ )) + suffix_ones return prefix_ones + ([0] * len(UpperCAmelCase__ )) + ([0] * len(UpperCAmelCase__ )) + suffix_ones def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = {self.convert_ids_to_tokens(UpperCAmelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = self.__dict__.copy() __SCREAMING_SNAKE_CASE = None return state def __setstate__( self : Union[str, Any] , UpperCAmelCase__ : Dict ) -> None: __SCREAMING_SNAKE_CASE = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = load_spm(self.spm_file , self.sp_model_kwargs ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE = Path(UpperCAmelCase__ ) if not save_dir.is_dir(): raise OSError(F"""{save_directory} should be a directory""" ) __SCREAMING_SNAKE_CASE = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) __SCREAMING_SNAKE_CASE = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , UpperCAmelCase__ ) if os.path.abspath(self.spm_file ) != os.path.abspath(UpperCAmelCase__ ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , UpperCAmelCase__ ) elif not os.path.isfile(self.spm_file ): with open(UpperCAmelCase__ , "wb" ) as fi: __SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase__ ) return (str(UpperCAmelCase__ ), str(UpperCAmelCase__ )) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str = "en" , UpperCAmelCase__ : Optional[List[str]] = None , UpperCAmelCase__ : str = "ro" , **UpperCAmelCase__ : str , ) -> BatchEncoding: __SCREAMING_SNAKE_CASE = src_lang __SCREAMING_SNAKE_CASE = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[str] , UpperCAmelCase__ : Optional[str] , **UpperCAmelCase__ : Dict ) -> Tuple: if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) __SCREAMING_SNAKE_CASE = src_lang __SCREAMING_SNAKE_CASE = self(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_lang_id(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tgt_lang_id return inputs def UpperCAmelCase_ ( self : Tuple ) -> Tuple: self.set_src_lang_special_tokens(self.src_lang ) def UpperCAmelCase_ ( self : int ) -> Optional[int]: self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> None: __SCREAMING_SNAKE_CASE = self.get_lang_token(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.lang_token_to_id[lang_token] __SCREAMING_SNAKE_CASE = [self.cur_lang_id] __SCREAMING_SNAKE_CASE = [self.eos_token_id] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : str ) -> None: __SCREAMING_SNAKE_CASE = self.get_lang_token(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.lang_token_to_id[lang_token] __SCREAMING_SNAKE_CASE = [self.cur_lang_id] __SCREAMING_SNAKE_CASE = [self.eos_token_id] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> str: return self.lang_code_to_token[lang] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : str ) -> int: __SCREAMING_SNAKE_CASE = self.get_lang_token(UpperCAmelCase__ ) return self.lang_token_to_id[lang_token] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = sentencepiece.SentencePieceProcessor(**lowerCAmelCase_ ) spm.Load(str(lowerCAmelCase_ ) ) return spm def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' with open(lowerCAmelCase_ , "r" ) as f: return json.load(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' with open(lowerCAmelCase_ , "w" ) as f: json.dump(lowerCAmelCase_ , lowerCAmelCase_ , indent=2 )
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 384 if "tiny" in model_name: __SCREAMING_SNAKE_CASE = [3, 3, 9, 3] __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if "small" in model_name: __SCREAMING_SNAKE_CASE = [3, 3, 27, 3] __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] if "base" in model_name: __SCREAMING_SNAKE_CASE = [3, 3, 27, 3] __SCREAMING_SNAKE_CASE = [128, 256, 512, 1024] __SCREAMING_SNAKE_CASE = 512 if "large" in model_name: __SCREAMING_SNAKE_CASE = [3, 3, 27, 3] __SCREAMING_SNAKE_CASE = [192, 384, 768, 1536] __SCREAMING_SNAKE_CASE = 768 if "xlarge" in model_name: __SCREAMING_SNAKE_CASE = [3, 3, 27, 3] __SCREAMING_SNAKE_CASE = [256, 512, 1024, 2048] __SCREAMING_SNAKE_CASE = 1024 # set label information __SCREAMING_SNAKE_CASE = 150 __SCREAMING_SNAKE_CASE = "huggingface/label-files" __SCREAMING_SNAKE_CASE = "ade20k-id2label.json" __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 = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = ConvNextConfig( depths=lowerCAmelCase_ , hidden_sizes=lowerCAmelCase_ , out_features=["stage1", "stage2", "stage3", "stage4"] ) __SCREAMING_SNAKE_CASE = UperNetConfig( backbone_config=lowerCAmelCase_ , auxiliary_in_channels=lowerCAmelCase_ , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid=lowerCAmelCase_ , ) return config def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] # fmt: off # stem rename_keys.append(("backbone.downsample_layers.0.0.weight", "backbone.embeddings.patch_embeddings.weight") ) rename_keys.append(("backbone.downsample_layers.0.0.bias", "backbone.embeddings.patch_embeddings.bias") ) rename_keys.append(("backbone.downsample_layers.0.1.weight", "backbone.embeddings.layernorm.weight") ) rename_keys.append(("backbone.downsample_layers.0.1.bias", "backbone.embeddings.layernorm.bias") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"""backbone.stages.{i}.{j}.gamma""", f"""backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.depthwise_conv.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.dwconv.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.norm.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.norm.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.layernorm.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv1.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.weight""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight""") ) rename_keys.append((f"""backbone.stages.{i}.{j}.pointwise_conv2.bias""", f"""backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias""") ) if i > 0: rename_keys.append((f"""backbone.downsample_layers.{i}.0.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.weight""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.0.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.0.bias""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.1.weight""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.weight""") ) rename_keys.append((f"""backbone.downsample_layers.{i}.1.bias""", f"""backbone.encoder.stages.{i}.downsampling_layer.1.bias""") ) rename_keys.append((f"""backbone.norm{i}.weight""", f"""backbone.hidden_states_norms.stage{i+1}.weight""") ) rename_keys.append((f"""backbone.norm{i}.bias""", f"""backbone.hidden_states_norms.stage{i+1}.bias""") ) # decode head rename_keys.extend( [ ("decode_head.conv_seg.weight", "decode_head.classifier.weight"), ("decode_head.conv_seg.bias", "decode_head.classifier.bias"), ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"), ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"), ] ) # fmt: on return rename_keys def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = dct.pop(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = val def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = { "upernet-convnext-tiny": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth", "upernet-convnext-small": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth", "upernet-convnext-base": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth", "upernet-convnext-large": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth", "upernet-convnext-xlarge": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth", } __SCREAMING_SNAKE_CASE = model_name_to_url[model_name] __SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(lowerCAmelCase_ , map_location="cpu" )["state_dict"] __SCREAMING_SNAKE_CASE = get_upernet_config(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = UperNetForSemanticSegmentation(lowerCAmelCase_ ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __SCREAMING_SNAKE_CASE = state_dict.pop(lowerCAmelCase_ ) if "bn" in key: __SCREAMING_SNAKE_CASE = key.replace("bn" , "batch_norm" ) __SCREAMING_SNAKE_CASE = val # rename keys __SCREAMING_SNAKE_CASE = create_rename_keys(lowerCAmelCase_ ) for src, dest in rename_keys: rename_key(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # verify on image __SCREAMING_SNAKE_CASE = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg" __SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ).convert("RGB" ) __SCREAMING_SNAKE_CASE = SegformerImageProcessor() __SCREAMING_SNAKE_CASE = processor(lowerCAmelCase_ , return_tensors="pt" ).pixel_values with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ ) if model_name == "upernet-convnext-tiny": __SCREAMING_SNAKE_CASE = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ) elif model_name == "upernet-convnext-small": __SCREAMING_SNAKE_CASE = torch.tensor( [[-8.8236, -8.8236, -8.6771], [-8.8236, -8.8236, -8.6771], [-8.7638, -8.7638, -8.6240]] ) elif model_name == "upernet-convnext-base": __SCREAMING_SNAKE_CASE = torch.tensor( [[-8.8558, -8.8558, -8.6905], [-8.8558, -8.8558, -8.6905], [-8.7669, -8.7669, -8.6021]] ) elif model_name == "upernet-convnext-large": __SCREAMING_SNAKE_CASE = torch.tensor( [[-8.6660, -8.6660, -8.6210], [-8.6660, -8.6660, -8.6210], [-8.6310, -8.6310, -8.5964]] ) elif model_name == "upernet-convnext-xlarge": __SCREAMING_SNAKE_CASE = torch.tensor( [[-8.4980, -8.4980, -8.3977], [-8.4980, -8.4980, -8.3977], [-8.4379, -8.4379, -8.3412]] ) print("Logits:" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , lowerCAmelCase_ , atol=1E-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase_ ) print(f"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(lowerCAmelCase_ ) if push_to_hub: print(f"""Pushing model and processor for {model_name} to hub""" ) model.push_to_hub(f"""openmmlab/{model_name}""" ) processor.push_to_hub(f"""openmmlab/{model_name}""" ) if __name__ == "__main__": a__ : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''upernet-convnext-tiny''', type=str, choices=[F"upernet-convnext-{size}" for size in ['''tiny''', '''small''', '''base''', '''large''', '''xlarge''']], help='''Name of the ConvNext UperNet 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__ : Any = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) a__ : Dict = { '''configuration_encodec''': [ '''ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''EncodecConfig''', ], '''feature_extraction_encodec''': ['''EncodecFeatureExtractor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ '''ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST''', '''EncodecModel''', '''EncodecPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys a__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""simple docstring""" import darl # noqa import gym import tqdm from diffusers.experimental import ValueGuidedRLPipeline a__ : Optional[Any] = { '''n_samples''': 6_4, '''horizon''': 3_2, '''num_inference_steps''': 2_0, '''n_guide_steps''': 2, # can set to 0 for faster sampling, does not use value network '''scale_grad_by_std''': True, '''scale''': 0.1, '''eta''': 0.0, '''t_grad_cutoff''': 2, '''device''': '''cpu''', } if __name__ == "__main__": a__ : Any = '''hopper-medium-v2''' a__ : Optional[Any] = gym.make(env_name) a__ : Dict = ValueGuidedRLPipeline.from_pretrained( '''bglick13/hopper-medium-v2-value-function-hor32''', env=env, ) env.seed(0) a__ : Optional[int] = env.reset() a__ : Any = 0 a__ : int = 0 a__ : Tuple = 1_0_0_0 a__ : Optional[int] = [obs.copy()] try: for t in tqdm.tqdm(range(T)): # call the policy a__ : Optional[Any] = pipeline(obs, planning_horizon=3_2) # execute action in environment a__ , a__ , a__ , a__ : Any = env.step(denorm_actions) a__ : List[Any] = env.get_normalized_score(total_reward) # update return total_reward += reward total_score += score print( F"Step: {t}, Reward: {reward}, Total Reward: {total_reward}, Score: {score}, Total Score:" F" {total_score}" ) # save observations for rendering rollout.append(next_observation.copy()) a__ : Optional[Any] = next_observation except KeyboardInterrupt: pass print(F"Total reward: {total_reward}")
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel a__ : List[Any] = logging.getLogger(__name__) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.path.exists(lowerCAmelCase_ ): if os.path.exists(os.path.join(lowerCAmelCase_ , "config.json" ) ) and os.path.isfile( os.path.join(lowerCAmelCase_ , "config.json" ) ): os.remove(os.path.join(lowerCAmelCase_ , "config.json" ) ) if os.path.exists(os.path.join(lowerCAmelCase_ , "pytorch_model.bin" ) ) and os.path.isfile( os.path.join(lowerCAmelCase_ , "pytorch_model.bin" ) ): os.remove(os.path.join(lowerCAmelCase_ , "pytorch_model.bin" ) ) else: os.makedirs(lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 2 if unlogit: __SCREAMING_SNAKE_CASE = torch.pow(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = p * torch.log(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 return -plogp.sum(dim=-1 ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' logger.info("lv, h >\t" + "\t".join(f"""{x + 1}""" for x in range(len(lowerCAmelCase_ ) ) ) ) for row in range(len(lowerCAmelCase_ ) ): if tensor.dtype != torch.long: logger.info(f"""layer {row + 1}:\t""" + "\t".join(f"""{x:.5f}""" for x in tensor[row].cpu().data ) ) else: logger.info(f"""layer {row + 1}:\t""" + "\t".join(f"""{x:d}""" for x in tensor[row].cpu().data ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=None , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model.config.num_hidden_layers, model.config.num_attention_heads __SCREAMING_SNAKE_CASE = torch.zeros(lowerCAmelCase_ , lowerCAmelCase_ ).to(args.device ) __SCREAMING_SNAKE_CASE = torch.zeros(lowerCAmelCase_ , lowerCAmelCase_ ).to(args.device ) if head_mask is None: __SCREAMING_SNAKE_CASE = torch.ones(lowerCAmelCase_ , lowerCAmelCase_ ).to(args.device ) head_mask.requires_grad_(requires_grad=lowerCAmelCase_ ) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = 0.0 __SCREAMING_SNAKE_CASE = 0.0 for step, inputs in enumerate(tqdm(lowerCAmelCase_ , desc="Iteration" , disable=args.local_rank not in [-1, 0] ) ): __SCREAMING_SNAKE_CASE = tuple(t.to(args.device ) for t in inputs ) ((__SCREAMING_SNAKE_CASE) , ) = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ , labels=lowerCAmelCase_ , head_mask=lowerCAmelCase_ ) # (loss), lm_logits, presents, (all hidden_states), (attentions) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = entropy(attn.detach() , lowerCAmelCase_ ) attn_entropy[layer] += masked_entropy.sum(-1 ).sum(0 ).sum(0 ).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(lowerCAmelCase_ ).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = torch.pow(torch.pow(lowerCAmelCase_ , lowerCAmelCase_ ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1E-20 if not args.dont_normalize_global_importance: __SCREAMING_SNAKE_CASE = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info("Attention entropies" ) print_ad_tensor(lowerCAmelCase_ ) if compute_importance: logger.info("Head importance scores" ) print_ad_tensor(lowerCAmelCase_ ) logger.info("Head ranked by importance scores" ) __SCREAMING_SNAKE_CASE = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) __SCREAMING_SNAKE_CASE = torch.arange( head_importance.numel() , device=args.device ) __SCREAMING_SNAKE_CASE = head_ranks.view_as(lowerCAmelCase_ ) print_ad_tensor(lowerCAmelCase_ ) return attn_entropy, head_importance, total_loss def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = compute_heads_importance(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , compute_entropy=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 1 / loss # instead of downsteam score use the LM loss logger.info("Pruning: original score: %f, threshold: %f" , lowerCAmelCase_ , original_score * args.masking_threshold ) __SCREAMING_SNAKE_CASE = torch.ones_like(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) __SCREAMING_SNAKE_CASE = original_score while current_score >= original_score * args.masking_threshold: __SCREAMING_SNAKE_CASE = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads __SCREAMING_SNAKE_CASE = float("Inf" ) __SCREAMING_SNAKE_CASE = head_importance.view(-1 ).sort()[1] if len(lowerCAmelCase_ ) <= num_to_mask: print("BREAK BY num_to_mask" ) break # mask heads __SCREAMING_SNAKE_CASE = current_heads_to_mask[:num_to_mask] logger.info("Heads to mask: %s" , str(current_heads_to_mask.tolist() ) ) __SCREAMING_SNAKE_CASE = new_head_mask.view(-1 ) __SCREAMING_SNAKE_CASE = 0.0 __SCREAMING_SNAKE_CASE = new_head_mask.view_as(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_head_mask.clone().detach() print_ad_tensor(lowerCAmelCase_ ) # Compute metric and head importance again __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = compute_heads_importance( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , compute_entropy=lowerCAmelCase_ , head_mask=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 1 / loss logger.info( "Masking: current score: %f, remaining heads %d (%.1f percents)" , lowerCAmelCase_ , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 100 , ) logger.info("Final head mask" ) print_ad_tensor(lowerCAmelCase_ ) np.save(os.path.join(args.output_dir , "head_mask.npy" ) , head_mask.detach().cpu().numpy() ) return head_mask def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = datetime.now() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = compute_heads_importance( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , compute_entropy=lowerCAmelCase_ , compute_importance=lowerCAmelCase_ , head_mask=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 1 / loss __SCREAMING_SNAKE_CASE = datetime.now() - before_time __SCREAMING_SNAKE_CASE = sum(p.numel() for p in model.parameters() ) __SCREAMING_SNAKE_CASE = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(lowerCAmelCase_ ) ) } for k, v in heads_to_prune.items(): if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [ v, ] assert sum(len(lowerCAmelCase_ ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum(p.numel() for p in model.parameters() ) __SCREAMING_SNAKE_CASE = datetime.now() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = compute_heads_importance( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , compute_entropy=lowerCAmelCase_ , compute_importance=lowerCAmelCase_ , head_mask=lowerCAmelCase_ , actually_pruned=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = 1 / loss __SCREAMING_SNAKE_CASE = datetime.now() - before_time logger.info( "Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)" , lowerCAmelCase_ , lowerCAmelCase_ , pruned_num_params / original_num_params * 100 , ) logger.info("Pruning: score with masking: %f score with pruning: %f" , lowerCAmelCase_ , lowerCAmelCase_ ) logger.info("Pruning: speed ratio (original timing / new timing): %f percents" , original_time / new_time * 100 ) save_model(lowerCAmelCase_ , args.output_dir ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( "--data_dir" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="The input data dir. Should contain the .tsv files (or other data files) for the task." , ) parser.add_argument( "--model_name_or_path" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--output_dir" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="The output directory where the model predictions and checkpoints will be written." , ) # Other parameters parser.add_argument( "--config_name" , default="" , type=lowerCAmelCase_ , help="Pretrained config name or path if not the same as model_name_or_path" , ) parser.add_argument( "--tokenizer_name" , default="" , type=lowerCAmelCase_ , help="Pretrained tokenizer name or path if not the same as model_name_or_path" , ) parser.add_argument( "--cache_dir" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="Where do you want to store the pre-trained models downloaded from s3" , ) parser.add_argument( "--data_subset" , type=lowerCAmelCase_ , default=-1 , help="If > 0: limit the data to a subset of data_subset instances." ) parser.add_argument( "--overwrite_output_dir" , action="store_true" , help="Whether to overwrite data in output directory" ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) parser.add_argument( "--dont_normalize_importance_by_layer" , action="store_true" , help="Don't normalize importance score by layers" ) parser.add_argument( "--dont_normalize_global_importance" , action="store_true" , help="Don't normalize all importance scores between 0 and 1" , ) parser.add_argument( "--try_masking" , action="store_true" , help="Whether to try to mask head until a threshold of accuracy." ) parser.add_argument( "--masking_threshold" , default=0.9 , type=lowerCAmelCase_ , help="masking threshold in term of metrics (stop masking when metric < threshold * original metric value)." , ) parser.add_argument( "--masking_amount" , default=0.1 , type=lowerCAmelCase_ , help="Amount to heads to masking at each masking step." ) parser.add_argument("--metric_name" , default="acc" , type=lowerCAmelCase_ , help="Metric to use for head masking." ) parser.add_argument( "--max_seq_length" , default=128 , type=lowerCAmelCase_ , help=( "The maximum total input sequence length after WordPiece tokenization. \n" "Sequences longer than this will be truncated, sequences shorter padded." ) , ) parser.add_argument("--batch_size" , default=1 , type=lowerCAmelCase_ , help="Batch size." ) parser.add_argument("--seed" , type=lowerCAmelCase_ , default=42 ) parser.add_argument("--local_rank" , type=lowerCAmelCase_ , default=-1 , help="local_rank for distributed training on gpus" ) parser.add_argument("--no_cuda" , action="store_true" , help="Whether not to use CUDA when available" ) parser.add_argument("--server_ip" , type=lowerCAmelCase_ , default="" , help="Can be used for distant debugging." ) parser.add_argument("--server_port" , type=lowerCAmelCase_ , default="" , help="Can be used for distant debugging." ) __SCREAMING_SNAKE_CASE = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach" ) ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=lowerCAmelCase_ ) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: __SCREAMING_SNAKE_CASE = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu" ) __SCREAMING_SNAKE_CASE = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) __SCREAMING_SNAKE_CASE = torch.device("cuda" , args.local_rank ) __SCREAMING_SNAKE_CASE = 1 torch.distributed.init_process_group(backend="nccl" ) # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN ) logger.info("device: {} n_gpu: {}, distributed: {}".format(args.device , args.n_gpu , bool(args.local_rank != -1 ) ) ) __SCREAMING_SNAKE_CASE = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: __SCREAMING_SNAKE_CASE = nn.parallel.DistributedDataParallel( lowerCAmelCase_ , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=lowerCAmelCase_ ) elif args.n_gpu > 1: __SCREAMING_SNAKE_CASE = nn.DataParallel(lowerCAmelCase_ ) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=lowerCAmelCase_ ) torch.save(lowerCAmelCase_ , os.path.join(args.output_dir , "run_args.bin" ) ) logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Prepare dataset __SCREAMING_SNAKE_CASE = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) __SCREAMING_SNAKE_CASE = (torch.from_numpy(lowerCAmelCase_ ),) __SCREAMING_SNAKE_CASE = TensorDataset(*lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = RandomSampler(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader(lowerCAmelCase_ , sampler=lowerCAmelCase_ , batch_size=args.batch_size ) # Compute head entropy and importance score compute_heads_importance(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: __SCREAMING_SNAKE_CASE = mask_heads(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) prune_heads(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, 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) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ ) 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(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * num_epochs) , ) # 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Union[str, Any] = { '''Salesforce/blip-vqa-base''': '''https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json''', '''Salesforce/blip-vqa-capfit-large''': ( '''https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-base''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-large''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json''' ), '''Salesforce/blip-itm-base-coco''': '''https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json''', '''Salesforce/blip-itm-large-coco''': '''https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json''', '''Salesforce/blip-itm-base-flikr''': '''https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json''', '''Salesforce/blip-itm-large-flikr''': ( '''https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "blip_text_model" def __init__( self : List[str] , UpperCAmelCase__ : Optional[int]=3_0_5_2_4 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : int=3_0_7_2 , UpperCAmelCase__ : Optional[int]=7_6_8 , UpperCAmelCase__ : Any=1_2 , UpperCAmelCase__ : Tuple=8 , UpperCAmelCase__ : List[Any]=5_1_2 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Dict=1E-12 , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : str=0.0 , UpperCAmelCase__ : Optional[Any]=0.02 , UpperCAmelCase__ : Optional[Any]=3_0_5_2_2 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Optional[Any]=1_0_2 , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=True , **UpperCAmelCase__ : List[Any] , ) -> Union[str, Any]: super().__init__( pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , sep_token_id=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = encoder_hidden_size __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = projection_dim __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = is_decoder __SCREAMING_SNAKE_CASE = use_cache @classmethod def UpperCAmelCase_ ( cls : List[str] , UpperCAmelCase__ : Union[str, os.PathLike] , **UpperCAmelCase__ : int ) -> "PretrainedConfig": cls._set_token_in_kwargs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = cls.get_config_dict(UpperCAmelCase__ , **UpperCAmelCase__ ) # get the text config dict if we are loading from BlipConfig if config_dict.get("model_type" ) == "blip": __SCREAMING_SNAKE_CASE = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(UpperCAmelCase__ , **UpperCAmelCase__ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[Any] = "blip_vision_model" def __init__( self : Tuple , UpperCAmelCase__ : List[Any]=7_6_8 , UpperCAmelCase__ : Tuple=3_0_7_2 , UpperCAmelCase__ : Tuple=5_1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : Optional[Any]=1_2 , UpperCAmelCase__ : int=3_8_4 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Any=1E-5 , UpperCAmelCase__ : Any=0.0 , UpperCAmelCase__ : Optional[Any]=1E-10 , **UpperCAmelCase__ : Optional[int] , ) -> Union[str, Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = projection_dim __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = attention_dropout __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = hidden_act @classmethod def UpperCAmelCase_ ( cls : List[Any] , UpperCAmelCase__ : Union[str, os.PathLike] , **UpperCAmelCase__ : Any ) -> "PretrainedConfig": cls._set_token_in_kwargs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = cls.get_config_dict(UpperCAmelCase__ , **UpperCAmelCase__ ) # get the vision config dict if we are loading from BlipConfig if config_dict.get("model_type" ) == "blip": __SCREAMING_SNAKE_CASE = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(UpperCAmelCase__ , **UpperCAmelCase__ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : int = "blip" snake_case__ : int = True def __init__( self : Any , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Tuple=5_1_2 , UpperCAmelCase__ : List[str]=2.6_592 , UpperCAmelCase__ : Any=2_5_6 , **UpperCAmelCase__ : str , ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) if text_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values." ) if vision_config is None: __SCREAMING_SNAKE_CASE = {} logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values." ) __SCREAMING_SNAKE_CASE = BlipTextConfig(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BlipVisionConfig(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.vision_config.hidden_size __SCREAMING_SNAKE_CASE = projection_dim __SCREAMING_SNAKE_CASE = logit_scale_init_value __SCREAMING_SNAKE_CASE = 1.0 __SCREAMING_SNAKE_CASE = 0.02 __SCREAMING_SNAKE_CASE = image_text_hidden_size @classmethod def UpperCAmelCase_ ( cls : List[Any] , UpperCAmelCase__ : BlipTextConfig , UpperCAmelCase__ : BlipVisionConfig , **UpperCAmelCase__ : Optional[Any] ) -> Dict: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> int: __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = self.text_config.to_dict() __SCREAMING_SNAKE_CASE = self.vision_config.to_dict() __SCREAMING_SNAKE_CASE = self.__class__.model_type return output
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str]=7 , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : Optional[int]=1_8 , UpperCAmelCase__ : Any=3_0 , UpperCAmelCase__ : Any=4_0_0 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Dict=True , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = size if size is not None else {"height": 1_8, "width": 1_8} __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = min_resolution __SCREAMING_SNAKE_CASE = max_resolution __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = size __SCREAMING_SNAKE_CASE = apply_ocr def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = LayoutLMvaImageProcessor if is_pytesseract_available() else None def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessingTester(self ) @property def UpperCAmelCase_ ( self : Optional[int] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(UpperCAmelCase__ , "size" ) ) self.assertTrue(hasattr(UpperCAmelCase__ , "apply_ocr" ) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 1_8, "width": 1_8} ) __SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {"height": 4_2, "width": 4_2} ) def UpperCAmelCase_ ( self : str ) -> Dict: pass def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: # Initialize image_processing __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase__ ) self.assertIsInstance(encoding.boxes , UpperCAmelCase__ ) # Test batched __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: # Initialize image_processing __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: # Initialize image_processing __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: # with apply_OCR = True __SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessor() from datasets import load_dataset __SCREAMING_SNAKE_CASE = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) __SCREAMING_SNAKE_CASE = Image.open(ds[0]["file"] ).convert("RGB" ) __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __SCREAMING_SNAKE_CASE = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 __SCREAMING_SNAKE_CASE = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase__ ) self.assertListEqual(encoding.boxes , UpperCAmelCase__ ) # with apply_OCR = False __SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" 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 AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 a__ : Union[str, Any] = get_tests_dir('''fixtures''') class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: # A mock response for an HTTP head request to emulate server down __SCREAMING_SNAKE_CASE = mock.Mock() __SCREAMING_SNAKE_CASE = 5_0_0 __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = HTTPError __SCREAMING_SNAKE_CASE = {} # Download this model to make sure it's in the cache. __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request" , return_value=UpperCAmelCase__ ) as mock_head: __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit" ) # This check we did call the fake head request mock_head.assert_called() def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: # This test is for deprecated behavior and can be removed in v5 __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained( "https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json" ) def UpperCAmelCase_ ( self : Any ) -> Tuple: with self.assertRaises(UpperCAmelCase__ ): # config is in subfolder, the following should not work without specifying the subfolder __SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants" ) __SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained( "hf-internal-testing/stable-diffusion-all-variants" , subfolder="feature_extractor" ) self.assertIsNotNone(UpperCAmelCase__ ) @is_staging_test class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @classmethod def UpperCAmelCase_ ( cls : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = TOKEN HfFolder.save_token(UpperCAmelCase__ ) @classmethod def UpperCAmelCase_ ( cls : str ) -> int: try: delete_repo(token=cls._token , repo_id="test-image-processor" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-image-processor-org" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="test-dynamic-image-processor" ) except HTTPError: pass def UpperCAmelCase_ ( self : Optional[int] ) -> str: __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained(UpperCAmelCase__ ) image_processor.push_to_hub("test-image-processor" , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) # Reset repo delete_repo(token=self._token , repo_id="test-image-processor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( UpperCAmelCase__ , repo_id="test-image-processor" , push_to_hub=UpperCAmelCase__ , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained(F"""{USER}/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained(UpperCAmelCase__ ) image_processor.push_to_hub("valid_org/test-image-processor" , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained("valid_org/test-image-processor" ) for k, v in image_processor.__dict__.items(): self.assertEqual(UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-image-processor" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( UpperCAmelCase__ , repo_id="valid_org/test-image-processor-org" , push_to_hub=UpperCAmelCase__ , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE = ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org" ) for k, v in image_processor.__dict__.items(): self.assertEqual(UpperCAmelCase__ , getattr(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: CustomImageProcessor.register_for_auto_class() __SCREAMING_SNAKE_CASE = CustomImageProcessor.from_pretrained(UpperCAmelCase__ ) image_processor.push_to_hub("test-dynamic-image-processor" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"} , ) __SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained( F"""{USER}/test-dynamic-image-processor""" , trust_remote_code=UpperCAmelCase__ ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , "CustomImageProcessor" )
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" import importlib.metadata from typing import Union from packaging.version import Version, parse from .constants import STR_OPERATION_TO_FUNC a__ : Tuple = parse(importlib.metadata.version('''torch''')) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if operation not in STR_OPERATION_TO_FUNC.keys(): raise ValueError(f"""`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}""" ) __SCREAMING_SNAKE_CASE = STR_OPERATION_TO_FUNC[operation] if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = parse(importlib.metadata.version(lowerCAmelCase_ ) ) return operation(lowerCAmelCase_ , parse(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return compare_versions(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def UpperCAmelCase_ ( self : List[Any] ) -> str: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""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 a__ : Optional[Any] = logging.getLogger() @unittest.skip("Temporarily disable the doc tests.") @require_torch @require_tf @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Path , UpperCAmelCase__ : Union[str, None] = None , UpperCAmelCase__ : Union[List[str], None] = None , UpperCAmelCase__ : Union[str, List[str], None] = None , UpperCAmelCase__ : bool = True , ) -> Any: __SCREAMING_SNAKE_CASE = [file for file in os.listdir(UpperCAmelCase__ ) if os.path.isfile(os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) )] if identifier is not None: __SCREAMING_SNAKE_CASE = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): for n_ in n_identifier: __SCREAMING_SNAKE_CASE = [file for file in files if n_ not in file] else: __SCREAMING_SNAKE_CASE = [file for file in files if n_identifier not in file] __SCREAMING_SNAKE_CASE = ignore_files or [] ignore_files.append("__init__.py" ) __SCREAMING_SNAKE_CASE = [file for file in files if file not in ignore_files] for file in files: # Open all files print("Testing" , UpperCAmelCase__ ) if only_modules: __SCREAMING_SNAKE_CASE = file.split("." )[0] try: __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = doctest.DocTestSuite(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = unittest.TextTestRunner().run(UpperCAmelCase__ ) self.assertIs(len(result.failures ) , 0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: __SCREAMING_SNAKE_CASE = doctest.testfile(str(".." / directory / file ) , optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed , 0 ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: __SCREAMING_SNAKE_CASE = Path("src/transformers" ) __SCREAMING_SNAKE_CASE = "modeling" __SCREAMING_SNAKE_CASE = [ "modeling_ctrl.py", "modeling_tf_ctrl.py", ] self.analyze_directory(UpperCAmelCase__ , identifier=UpperCAmelCase__ , ignore_files=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = Path("src/transformers" ) __SCREAMING_SNAKE_CASE = "tokenization" self.analyze_directory(UpperCAmelCase__ , identifier=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> str: __SCREAMING_SNAKE_CASE = Path("src/transformers" ) __SCREAMING_SNAKE_CASE = "configuration" self.analyze_directory(UpperCAmelCase__ , identifier=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = Path("src/transformers" ) __SCREAMING_SNAKE_CASE = ["configuration", "modeling", "tokenization"] self.analyze_directory(UpperCAmelCase__ , n_identifier=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[int]: __SCREAMING_SNAKE_CASE = Path("docs/source" ) __SCREAMING_SNAKE_CASE = ["favicon.ico"] self.analyze_directory(UpperCAmelCase__ , ignore_files=UpperCAmelCase__ , only_modules=UpperCAmelCase__ )
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" import unittest from transformers import AutoTokenizer, is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow if is_flax_available(): import jax.numpy as jnp from transformers import FlaxXLMRobertaModel @require_sentencepiece @require_tokenizers @require_flax class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = FlaxXLMRobertaModel.from_pretrained("xlm-roberta-base" ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("xlm-roberta-base" ) __SCREAMING_SNAKE_CASE = "The dog is cute and lives in the garden house" __SCREAMING_SNAKE_CASE = jnp.array([tokenizer.encode(UpperCAmelCase__ )] ) __SCREAMING_SNAKE_CASE = (1, 1_2, 7_6_8) # batch_size, sequence_length, embedding_vector_dim __SCREAMING_SNAKE_CASE = jnp.array( [[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )["last_hidden_state"] self.assertEqual(output.shape , UpperCAmelCase__ ) # compare the actual values for a slice of last dim self.assertTrue(jnp.allclose(output[:, :, -1] , UpperCAmelCase__ , atol=1E-3 ) )
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : List[str] = { '''facebook/timesformer''': '''https://huggingface.co/facebook/timesformer/resolve/main/config.json''', } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = "timesformer" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int]=2_2_4 , UpperCAmelCase__ : Tuple=1_6 , UpperCAmelCase__ : Any=3 , UpperCAmelCase__ : Dict=8 , UpperCAmelCase__ : List[Any]=7_6_8 , UpperCAmelCase__ : Union[str, Any]=1_2 , UpperCAmelCase__ : List[str]=1_2 , UpperCAmelCase__ : Optional[Any]=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Optional[int]=0.0 , UpperCAmelCase__ : int=0.0 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : List[Any]=1E-6 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str="divided_space_time" , UpperCAmelCase__ : List[str]=0 , **UpperCAmelCase__ : Union[str, Any] , ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = qkv_bias __SCREAMING_SNAKE_CASE = attention_type __SCREAMING_SNAKE_CASE = drop_path_rate
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration a__ : str = [ # tf -> hf ('''/''', '''.'''), ('''layer_''', '''layers.'''), ('''kernel''', '''weight'''), ('''beta''', '''bias'''), ('''gamma''', '''weight'''), ('''pegasus''', '''model'''), ] a__ : Tuple = [ ('''.output.dense''', '''.fc2'''), ('''intermediate.LayerNorm''', '''final_layer_norm'''), ('''intermediate.dense''', '''fc1'''), ] a__ : str = ( INIT_COMMON + [ ('''attention.self.LayerNorm''', '''self_attn_layer_norm'''), ('''attention.output.dense''', '''self_attn.out_proj'''), ('''attention.self''', '''self_attn'''), ('''attention.encdec.LayerNorm''', '''encoder_attn_layer_norm'''), ('''attention.encdec_output.dense''', '''encoder_attn.out_proj'''), ('''attention.encdec''', '''encoder_attn'''), ('''key''', '''k_proj'''), ('''value''', '''v_proj'''), ('''query''', '''q_proj'''), ('''decoder.LayerNorm''', '''decoder.layernorm_embedding'''), ] + END_COMMON ) a__ : Dict = ( INIT_COMMON + [ ('''embeddings.word_embeddings''', '''shared.weight'''), ('''embeddings.position_embeddings''', '''embed_positions.weight'''), ('''attention.self.LayerNorm''', '''self_attn_layer_norm'''), ('''attention.output.dense''', '''self_attn.output'''), ('''attention.self''', '''self_attn.self'''), ('''encoder.LayerNorm''', '''encoder.layernorm_embedding'''), ] + END_COMMON ) a__ : List[str] = [ '''encdec/key/bias''', '''encdec/query/bias''', '''encdec/value/bias''', '''self/key/bias''', '''self/query/bias''', '''self/value/bias''', '''encdec_output/dense/bias''', '''attention/output/dense/bias''', ] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' for tf_name, hf_name in patterns: __SCREAMING_SNAKE_CASE = k.replace(lowerCAmelCase_ , lowerCAmelCase_ ) return k def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = BigBirdPegasusConfig(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = BigBirdPegasusForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = torch_model.state_dict() __SCREAMING_SNAKE_CASE = {} # separating decoder weights __SCREAMING_SNAKE_CASE = {k: tf_weights[k] for k in tf_weights if k.startswith("pegasus/decoder" )} __SCREAMING_SNAKE_CASE = {k: tf_weights[k] for k in tf_weights if not k.startswith("pegasus/decoder" )} for k, v in tqdm(decoder_weights.items() , "tf -> hf conversion" ): __SCREAMING_SNAKE_CASE = [k.endswith(lowerCAmelCase_ ) for ending in KEYS_TO_IGNORE] if any(lowerCAmelCase_ ): continue __SCREAMING_SNAKE_CASE = DECODER_PATTERNS __SCREAMING_SNAKE_CASE = rename_state_dict_key(lowerCAmelCase_ , lowerCAmelCase_ ) if new_k not in state_dict: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): __SCREAMING_SNAKE_CASE = v.T __SCREAMING_SNAKE_CASE = torch.from_numpy(lowerCAmelCase_ ) assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" for k, v in tqdm(remaining_weights.items() , "tf -> hf conversion" ): __SCREAMING_SNAKE_CASE = [k.endswith(lowerCAmelCase_ ) for ending in KEYS_TO_IGNORE] if any(lowerCAmelCase_ ): continue __SCREAMING_SNAKE_CASE = REMAINING_PATTERNS __SCREAMING_SNAKE_CASE = rename_state_dict_key(lowerCAmelCase_ , lowerCAmelCase_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if any(True if i in k else False for i in ["dense", "query", "key", "value"] ): __SCREAMING_SNAKE_CASE = v.T __SCREAMING_SNAKE_CASE = torch.from_numpy(lowerCAmelCase_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f"""{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}""" __SCREAMING_SNAKE_CASE = mapping["model.embed_positions.weight"] __SCREAMING_SNAKE_CASE = mapping.pop("model.embed_positions.weight" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = torch_model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [ k for k in missing if k not in [ "final_logits_bias", "model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight", ] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tf.train.list_variables(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = ["global_step"] for name, shape in tqdm(lowerCAmelCase_ , desc="converting tf checkpoint to dict" ): __SCREAMING_SNAKE_CASE = any(pat in name for pat in ignore_name ) if skip_key: continue __SCREAMING_SNAKE_CASE = tf.train.load_variable(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = array return tf_weights def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_tf_weights_as_numpy(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = convert_bigbird_pegasus(lowerCAmelCase_ , lowerCAmelCase_ ) torch_model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() parser.add_argument('''--tf_ckpt_path''', type=str, help='''passed to tf.train.list_variables''') parser.add_argument('''--save_dir''', default=None, type=str, help='''Path to the output PyTorch model.''') a__ : str = parser.parse_args() a__ : Optional[Any] = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : UNetaDModel snake_case__ : ScoreSdeVeScheduler def __init__( self : int , UpperCAmelCase__ : UNetaDModel , UpperCAmelCase__ : ScoreSdeVeScheduler ) -> List[Any]: super().__init__() self.register_modules(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) @torch.no_grad() def __call__( self : List[str] , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 2_0_0_0 , UpperCAmelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCAmelCase__ : Optional[str] = "pil" , UpperCAmelCase__ : bool = True , **UpperCAmelCase__ : str , ) -> Union[ImagePipelineOutput, Tuple]: __SCREAMING_SNAKE_CASE = self.unet.config.sample_size __SCREAMING_SNAKE_CASE = (batch_size, 3, img_size, img_size) __SCREAMING_SNAKE_CASE = self.unet __SCREAMING_SNAKE_CASE = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ ) * self.scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE = sample.to(self.device ) self.scheduler.set_timesteps(UpperCAmelCase__ ) self.scheduler.set_sigmas(UpperCAmelCase__ ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): __SCREAMING_SNAKE_CASE = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): __SCREAMING_SNAKE_CASE = self.unet(UpperCAmelCase__ , UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = self.scheduler.step_correct(UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__ ).prev_sample # prediction step __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = self.scheduler.step_pred(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , generator=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = output.prev_sample, output.prev_sample_mean __SCREAMING_SNAKE_CASE = sample_mean.clamp(0 , 1 ) __SCREAMING_SNAKE_CASE = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __SCREAMING_SNAKE_CASE = self.numpy_to_pil(UpperCAmelCase__ ) if not return_dict: return (sample,) return ImagePipelineOutput(images=UpperCAmelCase__ )
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" import math import tensorflow as tf from packaging import version def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = tf.cast(math.pi , x.dtype ) __SCREAMING_SNAKE_CASE = tf.cast(0.044715 , x.dtype ) __SCREAMING_SNAKE_CASE = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(lowerCAmelCase_ , 3 )) )) return x * cdf def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(lowerCAmelCase_ ) return x * tf.tanh(tf.math.softplus(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = tf.cast(0.044715 , x.dtype ) __SCREAMING_SNAKE_CASE = tf.cast(0.7978845608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return tf.clip_by_value(_gelu(lowerCAmelCase_ ) , -10 , 10 ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_=-1 ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.split(lowerCAmelCase_ , 2 , axis=lowerCAmelCase_ ) return a * tf.math.sigmoid(lowerCAmelCase_ ) if version.parse(tf.version.VERSION) >= version.parse('''2.4'''): def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return tf.keras.activations.gelu(lowerCAmelCase_ , approximate=lowerCAmelCase_ ) a__ : Optional[Any] = tf.keras.activations.gelu a__ : str = approximate_gelu_wrap else: a__ : Tuple = _gelu a__ : int = _gelu_new a__ : List[Any] = { '''gelu''': gelu, '''gelu_10''': gelu_aa, '''gelu_fast''': gelu_fast, '''gelu_new''': gelu_new, '''glu''': glu, '''mish''': mish, '''quick_gelu''': quick_gelu, '''relu''': tf.keras.activations.relu, '''sigmoid''': tf.keras.activations.sigmoid, '''silu''': tf.keras.activations.swish, '''swish''': tf.keras.activations.swish, '''tanh''': tf.keras.activations.tanh, } def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) 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 UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=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 UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_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__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.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 UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : Optional[int] = logging.get_logger(__name__) a__ : List[str] = {'''vocab_file''': '''vocab.json'''} a__ : Optional[Any] = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } a__ : Optional[int] = {'''mgp-str''': 2_7} class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = VOCAB_FILES_NAMES snake_case__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any]="[GO]" , UpperCAmelCase__ : Dict="[GO]" , UpperCAmelCase__ : List[Any]="[s]" , UpperCAmelCase__ : Optional[int]="[GO]" , **UpperCAmelCase__ : Union[str, Any] ) -> Tuple: super().__init__( unk_token=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , **UpperCAmelCase__ , ) with open(UpperCAmelCase__ , encoding="utf-8" ) as vocab_handle: __SCREAMING_SNAKE_CASE = json.load(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {v: k for k, v in self.vocab.items()} @property def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: return len(self.vocab ) def UpperCAmelCase_ ( self : str ) -> List[str]: return dict(self.vocab , **self.added_tokens_encoder ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = [] for s in text: char_tokens.extend(UpperCAmelCase__ ) return char_tokens def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : int ) -> Any: return self.vocab.get(UpperCAmelCase__ , self.vocab.get(self.unk_token ) ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[Any] ) -> Optional[int]: return self.decoder.get(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCAmelCase__ ): logger.error("Vocabulary path ({}) should be a directory".format(UpperCAmelCase__ ) ) return __SCREAMING_SNAKE_CASE = os.path.join( UpperCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) with open(UpperCAmelCase__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) + "\n" ) return (vocab_file,)
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = int(lowerCAmelCase_ ) if n_element < 1: __SCREAMING_SNAKE_CASE = ValueError("a should be a positive number" ) raise my_error __SCREAMING_SNAKE_CASE = [1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = (0, 0, 0) __SCREAMING_SNAKE_CASE = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": a__ : Optional[Any] = input('''Enter the last number (nth term) of the Hamming Number Series: ''') print('''Formula of Hamming Number Series => 2^i * 3^j * 5^k''') a__ : Any = hamming(int(n)) print('''-----------------------------------------------------''') print(F"The list with nth numbers is: {hamming_numbers}") print('''-----------------------------------------------------''')
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" import copy import unittest from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_MULTIPLE_CHOICE_MAPPING, MODEL_FOR_QUESTION_ANSWERING_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, ) from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCamelCase_ : """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Union[str, Any]=7 , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Any=9_9 , UpperCAmelCase__ : Tuple=3_6 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : List[Any]=4 , UpperCAmelCase__ : Dict=3_7 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=5_1_2 , UpperCAmelCase__ : str=1_6 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : Dict=6 , UpperCAmelCase__ : int=6 , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Optional[Any]=1_0_0_0 , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = text_seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = coordinate_size __SCREAMING_SNAKE_CASE = shape_size __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __SCREAMING_SNAKE_CASE = text_seq_length __SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 + 1 __SCREAMING_SNAKE_CASE = self.text_seq_length + self.image_seq_length def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __SCREAMING_SNAKE_CASE = bbox[i, j, 3] __SCREAMING_SNAKE_CASE = bbox[i, j, 1] __SCREAMING_SNAKE_CASE = t if bbox[i, j, 2] < bbox[i, j, 0]: __SCREAMING_SNAKE_CASE = bbox[i, j, 2] __SCREAMING_SNAKE_CASE = bbox[i, j, 0] __SCREAMING_SNAKE_CASE = t __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.text_seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = LayoutLMvaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # text + image __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , pixel_values=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __SCREAMING_SNAKE_CASE = model(pixel_values=UpperCAmelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict ) -> Tuple: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = LayoutLMvaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = LayoutLMvaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Dict: __SCREAMING_SNAKE_CASE = LayoutLMvaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=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 UpperCAmelCase_ ( self : str ) -> Tuple: __SCREAMING_SNAKE_CASE = 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 ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = False snake_case__ : Any = False snake_case__ : Optional[int] = False snake_case__ : Optional[int] = ( ( LayoutLMvaModel, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaForQuestionAnswering, ) if is_torch_available() else () ) snake_case__ : Optional[int] = ( {"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel} if is_torch_available() else {} ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str ) -> List[Any]: # `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual # embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has # the sequence dimension of the text embedding only. # (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`) return True def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = LayoutLMvaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple=False ) -> Any: __SCREAMING_SNAKE_CASE = copy.deepcopy(UpperCAmelCase__ ) if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = { k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous() if isinstance(UpperCAmelCase__ , torch.Tensor ) and v.ndim > 1 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) elif model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) elif model_class in [ *get_values(UpperCAmelCase__ ), ]: __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) elif model_class in [ *get_values(UpperCAmelCase__ ), ]: __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=UpperCAmelCase__ , ) return inputs_dict def UpperCAmelCase_ ( self : Any ) -> str: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Tuple: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Any ) -> List[str]: for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = LayoutLMvaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @cached_property def UpperCAmelCase_ ( self : str ) -> Optional[Any]: return LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) if is_vision_available() else None @slow def UpperCAmelCase_ ( self : Dict ) -> Tuple: __SCREAMING_SNAKE_CASE = LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=UpperCAmelCase__ , return_tensors="pt" ).pixel_values.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 2]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 ) # forward pass __SCREAMING_SNAKE_CASE = model( input_ids=input_ids.to(UpperCAmelCase__ ) , bbox=bbox.to(UpperCAmelCase__ ) , pixel_values=pixel_values.to(UpperCAmelCase__ ) , ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 1_9_9, 7_6_8) ) self.assertEqual(outputs.last_hidden_state.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) )
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy 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 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def is_in_circle(lowerCAmelCase_ , lowerCAmelCase_ ) -> bool: __SCREAMING_SNAKE_CASE = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle __SCREAMING_SNAKE_CASE = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(lowerCAmelCase_ ) ) # The ratio of the area for circle to square is pi/4. __SCREAMING_SNAKE_CASE = proportion * 4 print(f"""The estimated value of pi is {pi_estimate}""" ) print(f"""The numpy value of pi is {pi}""" ) print(f"""The total error is {abs(pi - pi_estimate )}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 0.0 , lowerCAmelCase_ = 1.0 , ): '''simple docstring''' return mean( function_to_integrate(uniform(lowerCAmelCase_ , lowerCAmelCase_ ) ) for _ in range(lowerCAmelCase_ ) ) * (max_value - min_value) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 0.0 , lowerCAmelCase_ = 1.0 ): '''simple docstring''' def identity_function(lowerCAmelCase_ ) -> float: return x __SCREAMING_SNAKE_CASE = area_under_curve_estimator( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = (max_value * max_value - min_value * min_value) / 2 print("******************" ) print(f"""Estimating area under y=x where x varies from {min_value} to {max_value}""" ) print(f"""Estimated value is {estimated_value}""" ) print(f"""Expected value is {expected_value}""" ) print(f"""Total error is {abs(estimated_value - expected_value )}""" ) print("******************" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def function_to_integrate(lowerCAmelCase_ ) -> float: return sqrt(4.0 - x * x ) __SCREAMING_SNAKE_CASE = area_under_curve_estimator( lowerCAmelCase_ , lowerCAmelCase_ , 0.0 , 2.0 ) print("******************" ) print("Estimating pi using area_under_curve_estimator" ) print(f"""Estimated value is {estimated_value}""" ) print(f"""Expected value is {pi}""" ) print(f"""Total error is {abs(estimated_value - pi )}""" ) print("******************" ) if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "block_out_channels": [3_2, 6_4], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if n == 1 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return 0 elif n == 2: return 1 else: __SCREAMING_SNAKE_CASE = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 2 while digits < n: index += 1 __SCREAMING_SNAKE_CASE = len(str(fibonacci(lowerCAmelCase_ ) ) ) return index def UpperCAmelCase__ (lowerCAmelCase_ = 1000 ): '''simple docstring''' return fibonacci_digits_index(lowerCAmelCase_ ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" import heapq def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] # 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(lowerCAmelCase_ , [-1 * len(lowerCAmelCase_ ), (key, value)] ) # chosen_vertices = set of chosen vertices __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = heapq.heappop(lowerCAmelCase_ )[1][0] chosen_vertices.add(lowerCAmelCase_ ) # 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]: __SCREAMING_SNAKE_CASE = elem[1][1].index(lowerCAmelCase_ ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowerCAmelCase_ ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() a__ : Any = {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)}")
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([hex(lowerCAmelCase_ )[2:].zfill(2 ).upper() for byte in list(lowerCAmelCase_ )] ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if (len(lowerCAmelCase_ ) % 2) != 0: raise ValueError( "Base16 encoded data is invalid:\nData does not have an even number of hex digits." ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(lowerCAmelCase_ ) <= set("0123456789ABCDEF" ): raise ValueError( "Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters." ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 16 ) for i in range(0 , len(lowerCAmelCase_ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, 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) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ ) 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(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * num_epochs) , ) # 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : int = {'''configuration_ibert''': ['''IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''IBertConfig''', '''IBertOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[int] = [ '''IBERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''IBertForMaskedLM''', '''IBertForMultipleChoice''', '''IBertForQuestionAnswering''', '''IBertForSequenceClassification''', '''IBertForTokenClassification''', '''IBertModel''', '''IBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys a__ : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : Dict = { '''uw-madison/mra-base-512-4''': '''https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json''', } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = "mra" def __init__( self : Optional[Any] , UpperCAmelCase__ : Any=5_0_2_6_5 , UpperCAmelCase__ : Union[str, Any]=7_6_8 , UpperCAmelCase__ : Any=1_2 , UpperCAmelCase__ : Optional[Any]=1_2 , UpperCAmelCase__ : List[Any]=3_0_7_2 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : List[Any]=5_1_2 , UpperCAmelCase__ : Optional[Any]=1 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : Dict=1E-5 , UpperCAmelCase__ : Union[str, Any]="absolute" , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : Union[str, Any]="full" , UpperCAmelCase__ : Dict=0 , UpperCAmelCase__ : Optional[int]=0 , UpperCAmelCase__ : List[str]=1 , UpperCAmelCase__ : Optional[int]=0 , UpperCAmelCase__ : List[Any]=2 , **UpperCAmelCase__ : str , ) -> List[str]: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = block_per_row __SCREAMING_SNAKE_CASE = approx_mode __SCREAMING_SNAKE_CASE = initial_prior_first_n_blocks __SCREAMING_SNAKE_CASE = initial_prior_diagonal_n_blocks
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig 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 ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any]=1_3 , UpperCAmelCase__ : Union[str, Any]=3_0 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : Any=3 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Optional[int]=3_2 , UpperCAmelCase__ : List[Any]=5 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : Any="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=1_0 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Tuple=3 , UpperCAmelCase__ : List[Any]=0.6 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = mask_ratio __SCREAMING_SNAKE_CASE = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) __SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 __SCREAMING_SNAKE_CASE = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self : Any ) -> int: return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = ViTMAEModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = ViTMAEForPreTraining(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (self.image_size // self.patch_size) ** 2 __SCREAMING_SNAKE_CASE = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = ViTMAEForPreTraining(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () snake_case__ : Optional[int] = {"feature-extraction": ViTMAEModel} if is_torch_available() else {} snake_case__ : int = False snake_case__ : Union[str, Any] = False snake_case__ : Optional[int] = False snake_case__ : str = False def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = ViTMAEModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Dict ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason="ViTMAE does not use inputs_embeds" ) def UpperCAmelCase_ ( self : Dict ) -> int: pass def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict ) -> Optional[Any]: # make masks reproducible np.random.seed(2 ) __SCREAMING_SNAKE_CASE = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) __SCREAMING_SNAKE_CASE = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) __SCREAMING_SNAKE_CASE = torch.from_numpy(UpperCAmelCase__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument __SCREAMING_SNAKE_CASE = pt_noise super().check_pt_tf_models(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = outputs[0].cpu().numpy() __SCREAMING_SNAKE_CASE = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model_class.from_pretrained(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) # Make sure we don't have nans __SCREAMING_SNAKE_CASE = after_outputs[0].cpu().numpy() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCAmelCase__ , 1E-5 ) @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: pass @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def UpperCAmelCase_ ( self : Tuple ) -> str: pass @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: pass @unittest.skip(reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load" ) def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: pass @slow def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = ViTMAEModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @cached_property def UpperCAmelCase_ ( self : int ) -> Optional[Any]: return ViTImageProcessor.from_pretrained("facebook/vit-mae-base" ) if is_vision_available() else None @slow def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: # make random mask reproducible across the PT and TF model np.random.seed(2 ) __SCREAMING_SNAKE_CASE = ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=UpperCAmelCase__ , return_tensors="pt" ).to(UpperCAmelCase__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) __SCREAMING_SNAKE_CASE = ViTMAEConfig() __SCREAMING_SNAKE_CASE = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) __SCREAMING_SNAKE_CASE = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ , noise=torch.from_numpy(UpperCAmelCase__ ).to(device=UpperCAmelCase__ ) ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 1_9_6, 7_6_8) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(UpperCAmelCase__ ) , atol=1E-4 ) )
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def UpperCAmelCase_ ( self : List[Any] ) -> str: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = 2_5_0 __SCREAMING_SNAKE_CASE = ids_tensor((batch_size, length) , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.ones((batch_size, length) , device=UpperCAmelCase__ , dtype=torch.float ) / length return input_ids, scores def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(5 ) __SCREAMING_SNAKE_CASE = StoppingCriteriaList( [ MaxLengthCriteria(max_length=1_0 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(9 ) self.assertFalse(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = MaxLengthCriteria(max_length=1_0 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(5 ) self.assertFalse(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(9 ) self.assertFalse(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(5 ) self.assertFalse(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(9 ) self.assertFalse(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 1_0 ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._get_tensors(5 ) __SCREAMING_SNAKE_CASE = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_0 ) with self.assertWarns(UpperCAmelCase__ ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_1 ) __SCREAMING_SNAKE_CASE = validate_stopping_criteria(StoppingCriteriaList() , 1_1 ) self.assertEqual(len(UpperCAmelCase__ ) , 1 )
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() a__ : int = logging.get_logger(__name__) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = original_name.split("." )[0] __SCREAMING_SNAKE_CASE = key.split("." ) __SCREAMING_SNAKE_CASE = int(key_list[key_list.index(lowerCAmelCase_ ) - 2] ) __SCREAMING_SNAKE_CASE = int(key_list[key_list.index(lowerCAmelCase_ ) - 1] ) __SCREAMING_SNAKE_CASE = orig_block_num - offset __SCREAMING_SNAKE_CASE = key.replace(f"""{orig_block_num}.{layer_num}.{original_name}""" , f"""block.{new_block_num}.{layer_num}.{new_name}""" ) return key def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = OrderedDict() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0, 0 for key, value in state_dict.items(): if key.startswith("network" ): __SCREAMING_SNAKE_CASE = key.replace("network" , "poolformer.encoder" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("bias" ) and "patch_embed" not in key: patch_emb_offset += 1 __SCREAMING_SNAKE_CASE = key[: key.find("proj" )] __SCREAMING_SNAKE_CASE = key.replace(lowerCAmelCase_ , f"""patch_embeddings.{total_embed_found}.""" ) __SCREAMING_SNAKE_CASE = key.replace("proj" , "projection" ) if key.endswith("bias" ): total_embed_found += 1 if "patch_embeddings" in key: __SCREAMING_SNAKE_CASE = "poolformer.encoder." + key if "mlp.fc1" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "mlp.fc1" , "output.conv1" ) if "mlp.fc2" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "mlp.fc2" , "output.conv2" ) if "norm1" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "norm1" , "before_norm" ) if "norm2" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "norm2" , "after_norm" ) if "layer_scale_1" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "layer_scale_1" , "layer_scale_1" ) if "layer_scale_2" in key: __SCREAMING_SNAKE_CASE = replace_key_with_offset(lowerCAmelCase_ , lowerCAmelCase_ , "layer_scale_2" , "layer_scale_2" ) if "head" in key: __SCREAMING_SNAKE_CASE = key.replace("head" , "classifier" ) __SCREAMING_SNAKE_CASE = value return new_state_dict def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = "http://images.cocodataset.org/val2017/000000039769.jpg" __SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) return image @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = PoolFormerConfig() # set attributes based on model_name __SCREAMING_SNAKE_CASE = "huggingface/label-files" __SCREAMING_SNAKE_CASE = model_name[-3:] __SCREAMING_SNAKE_CASE = 1000 __SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" __SCREAMING_SNAKE_CASE = (1, 1000) # set config attributes __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()} if size == "s12": __SCREAMING_SNAKE_CASE = [2, 2, 6, 2] __SCREAMING_SNAKE_CASE = [64, 128, 320, 512] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 0.9 elif size == "s24": __SCREAMING_SNAKE_CASE = [4, 4, 12, 4] __SCREAMING_SNAKE_CASE = [64, 128, 320, 512] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 0.9 elif size == "s36": __SCREAMING_SNAKE_CASE = [6, 6, 18, 6] __SCREAMING_SNAKE_CASE = [64, 128, 320, 512] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 1E-6 __SCREAMING_SNAKE_CASE = 0.9 elif size == "m36": __SCREAMING_SNAKE_CASE = [6, 6, 18, 6] __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 1E-6 __SCREAMING_SNAKE_CASE = 0.95 elif size == "m48": __SCREAMING_SNAKE_CASE = [8, 8, 24, 8] __SCREAMING_SNAKE_CASE = [96, 192, 384, 768] __SCREAMING_SNAKE_CASE = 4.0 __SCREAMING_SNAKE_CASE = 1E-6 __SCREAMING_SNAKE_CASE = 0.95 else: raise ValueError(f"""Size {size} not supported""" ) # load image processor __SCREAMING_SNAKE_CASE = PoolFormerImageProcessor(crop_pct=lowerCAmelCase_ ) # Prepare image __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=lowerCAmelCase_ , return_tensors="pt" ).pixel_values logger.info(f"""Converting model {model_name}...""" ) # load original state dict __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location=torch.device("cpu" ) ) # rename keys __SCREAMING_SNAKE_CASE = rename_keys(lowerCAmelCase_ ) # create HuggingFace model and load state dict __SCREAMING_SNAKE_CASE = PoolFormerForImageClassification(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) model.eval() # Define image processor __SCREAMING_SNAKE_CASE = PoolFormerImageProcessor(crop_pct=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors="pt" ).pixel_values # forward pass __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits # define expected logit slices for different models if size == "s12": __SCREAMING_SNAKE_CASE = torch.tensor([-0.3045, -0.6758, -0.4869] ) elif size == "s24": __SCREAMING_SNAKE_CASE = torch.tensor([0.4402, -0.1374, -0.8045] ) elif size == "s36": __SCREAMING_SNAKE_CASE = torch.tensor([-0.6080, -0.5133, -0.5898] ) elif size == "m36": __SCREAMING_SNAKE_CASE = torch.tensor([0.3952, 0.2263, -1.2668] ) elif size == "m48": __SCREAMING_SNAKE_CASE = torch.tensor([0.1167, -0.0656, -0.3423] ) else: raise ValueError(f"""Size {size} not supported""" ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , lowerCAmelCase_ , atol=1E-2 ) # finally, save model and image processor logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}...""" ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path 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.''' ) a__ : Any = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer a__ : List[Any] = logging.get_logger(__name__) a__ : int = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Union[str, Any] = { '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } a__ : str = {'''allegro/herbert-base-cased''': 5_1_4} a__ : List[str] = {} class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : int = VOCAB_FILES_NAMES snake_case__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : str = PRETRAINED_INIT_CONFIGURATION snake_case__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Dict = HerbertTokenizer def __init__( self : int , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : int="<s>" , UpperCAmelCase__ : Dict="<unk>" , UpperCAmelCase__ : Tuple="<pad>" , UpperCAmelCase__ : List[str]="<mask>" , UpperCAmelCase__ : int="</s>" , **UpperCAmelCase__ : Optional[int] , ) -> Tuple: super().__init__( UpperCAmelCase__ , UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , **UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.cls_token_id] __SCREAMING_SNAKE_CASE = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None , UpperCAmelCase__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase__ , token_ids_a=UpperCAmelCase__ , already_has_special_tokens=UpperCAmelCase__ ) if token_ids_a is None: return [1] + ([0] * len(UpperCAmelCase__ )) + [1] return [1] + ([0] * len(UpperCAmelCase__ )) + [1] + ([0] * len(UpperCAmelCase__ )) + [1] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() a__ : Union[str, Any] = logging.get_logger(__name__) a__ : str = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = { "attention_cell": "multi_head", "num_layers": 4, "units": 1024, "hidden_size": 768, "max_length": 512, "num_heads": 8, "scaled": True, "dropout": 0.1, "use_residual": True, "embed_size": 1024, "embed_dropout": 0.1, "word_embed": None, "layer_norm_eps": 1E-5, "token_type_vocab_size": 2, } __SCREAMING_SNAKE_CASE = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __SCREAMING_SNAKE_CASE = BERTEncoder( attention_cell=predefined_args["attention_cell"] , num_layers=predefined_args["num_layers"] , units=predefined_args["units"] , hidden_size=predefined_args["hidden_size"] , max_length=predefined_args["max_length"] , num_heads=predefined_args["num_heads"] , scaled=predefined_args["scaled"] , dropout=predefined_args["dropout"] , output_attention=lowerCAmelCase_ , output_all_encodings=lowerCAmelCase_ , use_residual=predefined_args["use_residual"] , activation=predefined_args.get("activation" , "gelu" ) , layer_norm_eps=predefined_args.get("layer_norm_eps" , lowerCAmelCase_ ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __SCREAMING_SNAKE_CASE = "openwebtext_ccnews_stories_books_cased" # Specify download folder to Gluonnlp's vocab __SCREAMING_SNAKE_CASE = os.path.join(get_home_dir() , "models" ) __SCREAMING_SNAKE_CASE = _load_vocab(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , cls=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = nlp.model.BERTModel( lowerCAmelCase_ , len(lowerCAmelCase_ ) , units=predefined_args["units"] , embed_size=predefined_args["embed_size"] , embed_dropout=predefined_args["embed_dropout"] , word_embed=predefined_args["word_embed"] , use_pooler=lowerCAmelCase_ , use_token_type_embed=lowerCAmelCase_ , token_type_vocab_size=predefined_args["token_type_vocab_size"] , use_classifier=lowerCAmelCase_ , use_decoder=lowerCAmelCase_ , ) original_bort.load_parameters(lowerCAmelCase_ , cast_dtype=lowerCAmelCase_ , ignore_extra=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = original_bort._collect_params_with_prefix() # Build our config 🤗 __SCREAMING_SNAKE_CASE = { "architectures": ["BertForMaskedLM"], "attention_probs_dropout_prob": predefined_args["dropout"], "hidden_act": "gelu", "hidden_dropout_prob": predefined_args["dropout"], "hidden_size": predefined_args["embed_size"], "initializer_range": 0.02, "intermediate_size": predefined_args["hidden_size"], "layer_norm_eps": predefined_args["layer_norm_eps"], "max_position_embeddings": predefined_args["max_length"], "model_type": "bort", "num_attention_heads": predefined_args["num_heads"], "num_hidden_layers": predefined_args["num_layers"], "pad_token_id": 1, # 2 = BERT, 1 = RoBERTa "type_vocab_size": 1, # 2 = BERT, 1 = RoBERTa "vocab_size": len(lowerCAmelCase_ ), } __SCREAMING_SNAKE_CASE = BertConfig.from_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = BertForMaskedLM(lowerCAmelCase_ ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(lowerCAmelCase_ ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = hf_param.shape __SCREAMING_SNAKE_CASE = to_torch(params[gluon_param] ) __SCREAMING_SNAKE_CASE = gluon_param.shape assert ( shape_hf == shape_gluon ), f"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __SCREAMING_SNAKE_CASE = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , "word_embed.0.weight" ) __SCREAMING_SNAKE_CASE = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , "encoder.position_weight" ) __SCREAMING_SNAKE_CASE = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , "encoder.layer_norm.beta" ) __SCREAMING_SNAKE_CASE = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , "encoder.layer_norm.gamma" ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __SCREAMING_SNAKE_CASE = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __SCREAMING_SNAKE_CASE = hf_bort_model.bert.encoder.layer[i] # self attention __SCREAMING_SNAKE_CASE = layer.attention.self __SCREAMING_SNAKE_CASE = check_and_map_params( self_attn.key.bias.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( self_attn.key.weight.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( self_attn.query.bias.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( self_attn.query.weight.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( self_attn.value.bias.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( self_attn.value.weight.data , f"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __SCREAMING_SNAKE_CASE = layer.attention.output __SCREAMING_SNAKE_CASE = check_and_map_params( self_output.dense.bias , f"""encoder.transformer_cells.{i}.proj.bias""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( self_output.dense.weight , f"""encoder.transformer_cells.{i}.proj.weight""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( self_output.LayerNorm.bias , f"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( self_output.LayerNorm.weight , f"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __SCREAMING_SNAKE_CASE = layer.intermediate __SCREAMING_SNAKE_CASE = check_and_map_params( intermediate.dense.bias , f"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( intermediate.dense.weight , f"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __SCREAMING_SNAKE_CASE = layer.output __SCREAMING_SNAKE_CASE = check_and_map_params( bert_output.dense.bias , f"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( bert_output.dense.weight , f"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( bert_output.LayerNorm.bias , f"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __SCREAMING_SNAKE_CASE = check_and_map_params( bert_output.LayerNorm.weight , f"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __SCREAMING_SNAKE_CASE = RobertaTokenizer.from_pretrained("roberta-base" ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(lowerCAmelCase_ )["input_ids"] # Get gluon output __SCREAMING_SNAKE_CASE = mx.nd.array([input_ids] ) __SCREAMING_SNAKE_CASE = original_bort(inputs=lowerCAmelCase_ , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = BertModel.from_pretrained(lowerCAmelCase_ ) hf_bort_model.eval() __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(lowerCAmelCase_ , return_tensors="pt" ) __SCREAMING_SNAKE_CASE = hf_bort_model(**lowerCAmelCase_ )[0] __SCREAMING_SNAKE_CASE = output_gluon[0].asnumpy() __SCREAMING_SNAKE_CASE = output_hf[0].detach().numpy() __SCREAMING_SNAKE_CASE = np.max(np.abs(hf_layer - gluon_layer ) ).item() __SCREAMING_SNAKE_CASE = np.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1E-3 ) if success: print("✔️ Both model do output the same tensors" ) else: print("❌ Both model do **NOT** output the same tensors" ) print("Absolute difference is:" , lowerCAmelCase_ ) if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) a__ : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration a__ : Tuple = 5_0_0_0_0_0 a__ , a__ : str = os.path.split(__file__) a__ : Optional[int] = os.path.join(RESULTS_BASEPATH, '''results''', RESULTS_FILENAME.replace('''.py''', '''.json''')) @get_duration def UpperCAmelCase__ (lowerCAmelCase_ , **lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = dataset.map(**lowerCAmelCase_ ) @get_duration def UpperCAmelCase__ (lowerCAmelCase_ , **lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = dataset.filter(**lowerCAmelCase_ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = {"num examples": SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: __SCREAMING_SNAKE_CASE = datasets.Features({"text": datasets.Value("string" ), "numbers": datasets.Value("float32" )} ) __SCREAMING_SNAKE_CASE = generate_example_dataset( os.path.join(lowerCAmelCase_ , "dataset.arrow" ) , lowerCAmelCase_ , num_examples=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = transformers.AutoTokenizer.from_pretrained("bert-base-cased" , use_fast=lowerCAmelCase_ ) def tokenize(lowerCAmelCase_ ): return tokenizer(examples["text"] ) __SCREAMING_SNAKE_CASE = map(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = map(lowerCAmelCase_ , batched=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = map(lowerCAmelCase_ , function=lambda lowerCAmelCase_ : None , batched=lowerCAmelCase_ ) with dataset.formatted_as(type="numpy" ): __SCREAMING_SNAKE_CASE = map(lowerCAmelCase_ , function=lambda lowerCAmelCase_ : None , batched=lowerCAmelCase_ ) with dataset.formatted_as(type="pandas" ): __SCREAMING_SNAKE_CASE = map(lowerCAmelCase_ , function=lambda lowerCAmelCase_ : None , batched=lowerCAmelCase_ ) with dataset.formatted_as(type="torch" , columns="numbers" ): __SCREAMING_SNAKE_CASE = map(lowerCAmelCase_ , function=lambda lowerCAmelCase_ : None , batched=lowerCAmelCase_ ) with dataset.formatted_as(type="tensorflow" , columns="numbers" ): __SCREAMING_SNAKE_CASE = map(lowerCAmelCase_ , function=lambda lowerCAmelCase_ : None , batched=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = map(lowerCAmelCase_ , function=lowerCAmelCase_ , batched=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = filter(lowerCAmelCase_ ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(lowerCAmelCase_ , "wb" ) as f: f.write(json.dumps(lowerCAmelCase_ ).encode("utf-8" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) 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 UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=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 UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_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__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.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 UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str ) -> Optional[Any]: with open(UpperCAmelCase__ , encoding="utf-8" ) as input_file: __SCREAMING_SNAKE_CASE = re.compile(R"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) __SCREAMING_SNAKE_CASE = input_file.read() __SCREAMING_SNAKE_CASE = regexp.search(UpperCAmelCase__ ) return match def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : str ) -> Any: with open(UpperCAmelCase__ , encoding="utf-8" ) as input_file: __SCREAMING_SNAKE_CASE = re.compile(R"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) __SCREAMING_SNAKE_CASE = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` __SCREAMING_SNAKE_CASE = regexp.finditer(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def UpperCAmelCase_ ( self : int ) -> Tuple: __SCREAMING_SNAKE_CASE = Path("./datasets" ) __SCREAMING_SNAKE_CASE = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(UpperCAmelCase__ ) ): raise AssertionError(F"""open(...) must use utf-8 encoding in {dataset}""" ) def UpperCAmelCase_ ( self : Tuple ) -> List[str]: __SCREAMING_SNAKE_CASE = Path("./datasets" ) __SCREAMING_SNAKE_CASE = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(UpperCAmelCase__ ) ): raise AssertionError(F"""print statement found in {dataset}. Use datasets.logger/logging instead.""" )
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" # coding=utf-8 # Copyright 2023 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import platform import sys a__ : Optional[int] = '''3''' print('''Python version:''', sys.version) print('''OS platform:''', platform.platform()) print('''OS architecture:''', platform.machine()) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) except ImportError: print('''Torch version:''', None) try: import transformers print('''transformers version:''', transformers.__version__) except ImportError: print('''transformers version:''', None)
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" from __future__ import annotations a__ : Any = tuple[int, int, int] a__ : str = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase a__ : List[Any] = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' # -------------------------- default selection -------------------------- # rotors -------------------------- a__ : Union[str, Any] = '''EGZWVONAHDCLFQMSIPJBYUKXTR''' a__ : Tuple = '''FOBHMDKEXQNRAULPGSJVTYICZW''' a__ : Tuple = '''ZJXESIUQLHAVRMDOYGTNFWPBKC''' # reflector -------------------------- a__ : Optional[int] = { '''A''': '''N''', '''N''': '''A''', '''B''': '''O''', '''O''': '''B''', '''C''': '''P''', '''P''': '''C''', '''D''': '''Q''', '''Q''': '''D''', '''E''': '''R''', '''R''': '''E''', '''F''': '''S''', '''S''': '''F''', '''G''': '''T''', '''T''': '''G''', '''H''': '''U''', '''U''': '''H''', '''I''': '''V''', '''V''': '''I''', '''J''': '''W''', '''W''': '''J''', '''K''': '''X''', '''X''': '''K''', '''L''': '''Y''', '''Y''': '''L''', '''M''': '''Z''', '''Z''': '''M''', } # -------------------------- extra rotors -------------------------- a__ : Optional[Any] = '''RMDJXFUWGISLHVTCQNKYPBEZOA''' a__ : Optional[int] = '''SGLCPQWZHKXAREONTFBVIYJUDM''' a__ : Any = '''HVSICLTYKQUBXDWAJZOMFGPREN''' a__ : Optional[int] = '''RZWQHFMVDBKICJLNTUXAGYPSOE''' a__ : Dict = '''LFKIJODBEGAMQPXVUHYSTCZRWN''' a__ : List[str] = '''KOAEGVDHXPQZMLFTYWJNBRCIUS''' def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if (unique_rotsel := len(set(lowerCAmelCase_ ) )) < 3: __SCREAMING_SNAKE_CASE = f"""Please use 3 unique rotors (not {unique_rotsel})""" raise Exception(lowerCAmelCase_ ) # Checks if rotor positions are valid __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rotpos if not 0 < rotorposa <= len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""First rotor position is not within range of 1..26 ({rotorposa}""" raise ValueError(lowerCAmelCase_ ) if not 0 < rotorposa <= len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""Second rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(lowerCAmelCase_ ) if not 0 < rotorposa <= len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""Third rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(lowerCAmelCase_ ) # Validates string and returns dict __SCREAMING_SNAKE_CASE = _plugboard(lowerCAmelCase_ ) return rotpos, rotsel, pbdict def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""Plugboard setting isn't type string ({type(lowerCAmelCase_ )})""" raise TypeError(lowerCAmelCase_ ) elif len(lowerCAmelCase_ ) % 2 != 0: __SCREAMING_SNAKE_CASE = f"""Odd number of symbols ({len(lowerCAmelCase_ )})""" raise Exception(lowerCAmelCase_ ) elif pbstring == "": return {} pbstring.replace(" " , "" ) # Checks if all characters are unique __SCREAMING_SNAKE_CASE = set() for i in pbstring: if i not in abc: __SCREAMING_SNAKE_CASE = f"""'{i}' not in list of symbols""" raise Exception(lowerCAmelCase_ ) elif i in tmppbl: __SCREAMING_SNAKE_CASE = f"""Duplicate symbol ({i})""" raise Exception(lowerCAmelCase_ ) else: tmppbl.add(lowerCAmelCase_ ) del tmppbl # Created the dictionary __SCREAMING_SNAKE_CASE = {} for j in range(0 , len(lowerCAmelCase_ ) - 1 , 2 ): __SCREAMING_SNAKE_CASE = pbstring[j + 1] __SCREAMING_SNAKE_CASE = pbstring[j] return pb def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = (rotora, rotora, rotora) , lowerCAmelCase_ = "" , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = text.upper() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = _validator( lowerCAmelCase_ , lowerCAmelCase_ , plugb.upper() ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rotor_position __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 __SCREAMING_SNAKE_CASE = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: __SCREAMING_SNAKE_CASE = plugboard[symbol] # rotor ra -------------------------- __SCREAMING_SNAKE_CASE = abc.index(lowerCAmelCase_ ) + rotorposa __SCREAMING_SNAKE_CASE = rotora[index % len(lowerCAmelCase_ )] # rotor rb -------------------------- __SCREAMING_SNAKE_CASE = abc.index(lowerCAmelCase_ ) + rotorposa __SCREAMING_SNAKE_CASE = rotora[index % len(lowerCAmelCase_ )] # rotor rc -------------------------- __SCREAMING_SNAKE_CASE = abc.index(lowerCAmelCase_ ) + rotorposa __SCREAMING_SNAKE_CASE = rotora[index % len(lowerCAmelCase_ )] # reflector -------------------------- # this is the reason you don't need another machine to decipher __SCREAMING_SNAKE_CASE = reflector[symbol] # 2nd rotors __SCREAMING_SNAKE_CASE = abc[rotora.index(lowerCAmelCase_ ) - rotorposa] __SCREAMING_SNAKE_CASE = abc[rotora.index(lowerCAmelCase_ ) - rotorposa] __SCREAMING_SNAKE_CASE = abc[rotora.index(lowerCAmelCase_ ) - rotorposa] # 2nd plugboard if symbol in plugboard: __SCREAMING_SNAKE_CASE = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 0 rotorposa += 1 if rotorposa >= len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 0 rotorposa += 1 if rotorposa >= len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) if __name__ == "__main__": a__ : Union[str, Any] = '''This is my Python script that emulates the Enigma machine from WWII.''' a__ : str = (1, 1, 1) a__ : Any = '''pictures''' a__ : int = (rotora, rotora, rotora) a__ : Union[str, Any] = enigma(message, rotor_pos, rotor_sel, pb) print('''Encrypted message:''', en) print('''Decrypted message:''', enigma(en, rotor_pos, rotor_sel, pb))
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy 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 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""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 UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = ( ( TFMobileBertModel, TFMobileBertForMaskedLM, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertForMultipleChoice, ) if is_tf_available() else () ) snake_case__ : Union[str, Any] = ( { "feature-extraction": TFMobileBertModel, "fill-mask": TFMobileBertForMaskedLM, "question-answering": TFMobileBertForQuestionAnswering, "text-classification": TFMobileBertForSequenceClassification, "token-classification": TFMobileBertForTokenClassification, "zero-shot": TFMobileBertForSequenceClassification, } if is_tf_available() else {} ) snake_case__ : Union[str, Any] = False snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int=False ) -> Optional[int]: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) return inputs_dict class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str]=1_3 , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Dict=9_9 , UpperCAmelCase__ : str=3_2 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : Optional[Any]=4 , UpperCAmelCase__ : Tuple=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : Tuple=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : Any=3 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : str=None , ) -> Tuple: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = embedding_size def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE = TFMobileBertModel(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [input_ids, input_mask] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict ) -> Optional[int]: __SCREAMING_SNAKE_CASE = TFMobileBertForMaskedLM(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = TFMobileBertForNextSentencePrediction(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Any: __SCREAMING_SNAKE_CASE = TFMobileBertForPreTraining(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) 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 UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = TFMobileBertForSequenceClassification(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str ) -> Dict: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = TFMobileBertForMultipleChoice(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = TFMobileBertForTokenClassification(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = TFMobileBertForQuestionAnswering(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = model(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 UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = TFMobileBertModelTest.TFMobileBertModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[Any]: # for model_name in TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["google/mobilebert-uncased"]: __SCREAMING_SNAKE_CASE = TFMobileBertModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @require_tf class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> str: __SCREAMING_SNAKE_CASE = TFMobileBertForPreTraining.from_pretrained("google/mobilebert-uncased" ) __SCREAMING_SNAKE_CASE = tf.constant([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = [1, 6, 3_0_5_2_2] self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.constant( [ [ [-4.5_919_547, -9.248_295, -9.645_256], [-6.7_306_175, -6.440_284, -6.6_052_837], [-7.2_743_506, -6.7_847_915, -6.024_673], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 )
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "block_out_channels": [3_2, 6_4], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any]=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : Optional[Any]=9_9 , UpperCAmelCase__ : Tuple=3_2 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : str=0.1 , UpperCAmelCase__ : Tuple=5_1_2 , UpperCAmelCase__ : int=1_6 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : int=4 , UpperCAmelCase__ : Optional[Any]=None , ) -> List[Any]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = 1_3 __SCREAMING_SNAKE_CASE = 7 __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = 9_9 __SCREAMING_SNAKE_CASE = 3_2 __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3_7 __SCREAMING_SNAKE_CASE = "gelu" __SCREAMING_SNAKE_CASE = 0.1 __SCREAMING_SNAKE_CASE = 0.1 __SCREAMING_SNAKE_CASE = 5_1_2 __SCREAMING_SNAKE_CASE = 1_6 __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = 0.02 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = None def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=UpperCAmelCase__ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple ) -> List[str]: __SCREAMING_SNAKE_CASE = TFRoFormerModel(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = [input_ids, input_mask] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = TFRoFormerForCausalLM(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )["logits"] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = TFRoFormerForMaskedLM(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str ) -> Tuple: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = TFRoFormerForSequenceClassification(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = TFRoFormerForMultipleChoice(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = TFRoFormerForTokenClassification(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = TFRoFormerForQuestionAnswering(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } __SCREAMING_SNAKE_CASE = model(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 UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Dict = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) snake_case__ : Dict = ( { "feature-extraction": TFRoFormerModel, "fill-mask": TFRoFormerForMaskedLM, "question-answering": TFRoFormerForQuestionAnswering, "text-classification": TFRoFormerForSequenceClassification, "text-generation": TFRoFormerForCausalLM, "token-classification": TFRoFormerForTokenClassification, "zero-shot": TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) snake_case__ : Optional[int] = False snake_case__ : Optional[int] = False def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : int ) -> List[Any]: if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = TFRoFormerModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : List[Any] ) -> str: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : str ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> str: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = TFRoFormerModel.from_pretrained("junnyu/roformer_chinese_base" ) self.assertIsNotNone(UpperCAmelCase__ ) @require_tf class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = TFRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base" ) __SCREAMING_SNAKE_CASE = tf.constant([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] # TODO Replace vocab size __SCREAMING_SNAKE_CASE = 5_0_0_0_0 __SCREAMING_SNAKE_CASE = [1, 6, vocab_size] self.assertEqual(output.shape , UpperCAmelCase__ ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. __SCREAMING_SNAKE_CASE = tf.constant( [ [ [-0.12_053_341, -1.0_264_901, 0.29_221_946], [-1.5_133_783, 0.197_433, 0.15_190_607], [-5.0_135_403, -3.900_256, -0.84_038_764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) @require_tf class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" snake_case__ : int = 1E-4 def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = tf.constant([[4, 1_0]] ) __SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) __SCREAMING_SNAKE_CASE = emba(input_ids.shape ) __SCREAMING_SNAKE_CASE = tf.constant( [[0.0_000, 0.0_000, 0.0_000, 1.0_000, 1.0_000, 1.0_000], [0.8_415, 0.0_464, 0.0_022, 0.5_403, 0.9_989, 1.0_000]] ) tf.debugging.assert_near(UpperCAmelCase__ , UpperCAmelCase__ , atol=self.tolerance ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = tf.constant( [ [0.0_000, 0.0_000, 0.0_000, 0.0_000, 0.0_000], [0.8_415, 0.8_219, 0.8_020, 0.7_819, 0.7_617], [0.9_093, 0.9_364, 0.9_581, 0.9_749, 0.9_870], ] ) __SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=5_1_2 , embedding_dim=5_1_2 ) emba([2, 1_6, 5_1_2] ) __SCREAMING_SNAKE_CASE = emba.weight[:3, :5] tf.debugging.assert_near(UpperCAmelCase__ , UpperCAmelCase__ , atol=self.tolerance ) @require_tf class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" snake_case__ : Any = 1E-4 def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: # 2,12,16,64 __SCREAMING_SNAKE_CASE = tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 __SCREAMING_SNAKE_CASE = -tf.reshape(tf.range(2 * 1_2 * 1_6 * 6_4 , dtype=tf.floataa ) , shape=(2, 1_2, 1_6, 6_4) ) / 1_0_0 __SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=3_2 , embedding_dim=6_4 ) __SCREAMING_SNAKE_CASE = embed_positions([2, 1_6, 7_6_8] )[None, None, :, :] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = TFRoFormerSelfAttention.apply_rotary_position_embeddings( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.constant( [ [0.0_000, 0.0_100, 0.0_200, 0.0_300, 0.0_400, 0.0_500, 0.0_600, 0.0_700], [-0.2_012, 0.8_897, 0.0_263, 0.9_401, 0.2_074, 0.9_463, 0.3_481, 0.9_343], [-1.7_057, 0.6_271, -1.2_145, 1.3_897, -0.6_303, 1.7_647, -0.1_173, 1.8_985], [-2.1_731, -1.6_397, -2.7_358, 0.2_854, -2.1_840, 1.7_183, -1.3_018, 2.4_871], [0.2_717, -3.6_173, -2.9_206, -2.1_988, -3.6_638, 0.3_858, -2.9_155, 2.2_980], [3.9_859, -2.1_580, -0.7_984, -4.4_904, -4.1_181, -2.0_252, -4.4_782, 1.1_253], ] ) __SCREAMING_SNAKE_CASE = tf.constant( [ [0.0_000, -0.0_100, -0.0_200, -0.0_300, -0.0_400, -0.0_500, -0.0_600, -0.0_700], [0.2_012, -0.8_897, -0.0_263, -0.9_401, -0.2_074, -0.9_463, -0.3_481, -0.9_343], [1.7_057, -0.6_271, 1.2_145, -1.3_897, 0.6_303, -1.7_647, 0.1_173, -1.8_985], [2.1_731, 1.6_397, 2.7_358, -0.2_854, 2.1_840, -1.7_183, 1.3_018, -2.4_871], [-0.2_717, 3.6_173, 2.9_206, 2.1_988, 3.6_638, -0.3_858, 2.9_155, -2.2_980], [-3.9_859, 2.1_580, 0.7_984, 4.4_904, 4.1_181, 2.0_252, 4.4_782, -1.1_253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , UpperCAmelCase__ , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , UpperCAmelCase__ , atol=self.tolerance )
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations import math from collections.abc import Callable def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 100 , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = x_start __SCREAMING_SNAKE_CASE = fnc(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0.0 for _ in range(lowerCAmelCase_ ): # Approximates curve as a sequence of linear lines and sums their length __SCREAMING_SNAKE_CASE = (x_end - x_start) / steps + xa __SCREAMING_SNAKE_CASE = fnc(lowerCAmelCase_ ) length += math.hypot(xa - xa , fxa - fxa ) # Increment step __SCREAMING_SNAKE_CASE = xa __SCREAMING_SNAKE_CASE = fxa return length if __name__ == "__main__": def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return math.sin(10 * x ) print('''f(x) = sin(10 * x)''') print('''The length of the curve from x = -10 to x = 10 is:''') a__ : Tuple = 1_0 while i <= 1_0_0_0_0_0: print(F"With {i} steps: {line_length(f, -1_0, 1_0, i)}") i *= 1_0
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" import itertools import string from collections.abc import Generator, Iterable def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = iter(lowerCAmelCase_ ) while True: __SCREAMING_SNAKE_CASE = tuple(itertools.islice(lowerCAmelCase_ , lowerCAmelCase_ ) ) if not chunk: return yield chunk def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = "".join([c.upper() for c in dirty if c in string.ascii_letters] ) __SCREAMING_SNAKE_CASE = "" if len(lowerCAmelCase_ ) < 2: return dirty for i in range(len(lowerCAmelCase_ ) - 1 ): clean += dirty[i] if dirty[i] == dirty[i + 1]: clean += "X" clean += dirty[-1] if len(lowerCAmelCase_ ) & 1: clean += "X" return clean def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = "ABCDEFGHIKLMNOPQRSTUVWXYZ" # we're using a list instead of a '2d' array because it makes the math # for setting up the table and doing the actual encoding/decoding simpler __SCREAMING_SNAKE_CASE = [] # copy key chars into the table if they are in `alphabet` ignoring duplicates for char in key.upper(): if char not in table and char in alphabet: table.append(lowerCAmelCase_ ) # fill the rest of the table in with the remaining alphabet chars for char in alphabet: if char not in table: table.append(lowerCAmelCase_ ) return table def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = generate_table(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = prepare_input(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(lowerCAmelCase_ , 2 ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = divmod(table.index(lowerCAmelCase_ ) , 5 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = divmod(table.index(lowerCAmelCase_ ) , 5 ) if rowa == rowa: ciphertext += table[rowa * 5 + (cola + 1) % 5] ciphertext += table[rowa * 5 + (cola + 1) % 5] elif cola == cola: ciphertext += table[((rowa + 1) % 5) * 5 + cola] ciphertext += table[((rowa + 1) % 5) * 5 + cola] else: # rectangle ciphertext += table[rowa * 5 + cola] ciphertext += table[rowa * 5 + cola] return ciphertext def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = generate_table(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = "" # https://en.wikipedia.org/wiki/Playfair_cipher#Description for chara, chara in chunker(lowerCAmelCase_ , 2 ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = divmod(table.index(lowerCAmelCase_ ) , 5 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = divmod(table.index(lowerCAmelCase_ ) , 5 ) if rowa == rowa: plaintext += table[rowa * 5 + (cola - 1) % 5] plaintext += table[rowa * 5 + (cola - 1) % 5] elif cola == cola: plaintext += table[((rowa - 1) % 5) * 5 + cola] plaintext += table[((rowa - 1) % 5) * 5 + cola] else: # rectangle plaintext += table[rowa * 5 + cola] plaintext += table[rowa * 5 + cola] return plaintext
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow 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 numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class UpperCamelCase_ : """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : Optional[int] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = 1_3 __SCREAMING_SNAKE_CASE = 7 __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = 9_9 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 3_2 __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 0.1 __SCREAMING_SNAKE_CASE = 0.1 __SCREAMING_SNAKE_CASE = 5_1_2 __SCREAMING_SNAKE_CASE = 1_6 __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = 0.02 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = "last" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = 0 def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) __SCREAMING_SNAKE_CASE = None if self.use_input_lengths: __SCREAMING_SNAKE_CASE = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , ) -> str: __SCREAMING_SNAKE_CASE = TFFlaubertModel(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "lengths": input_lengths, "langs": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [input_ids, input_mask] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = TFFlaubertWithLMHeadModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "lengths": input_lengths, "langs": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = TFFlaubertForQuestionAnsweringSimple(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "lengths": input_lengths} __SCREAMING_SNAKE_CASE = model(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 UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , ) -> Any: __SCREAMING_SNAKE_CASE = TFFlaubertForSequenceClassification(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "lengths": input_lengths} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , ) -> Dict: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = TFFlaubertForTokenClassification(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = TFFlaubertForMultipleChoice(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.num_choices, 1) ) __SCREAMING_SNAKE_CASE = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, "token_type_ids": multiple_choice_token_type_ids, } __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : str ) -> Tuple: __SCREAMING_SNAKE_CASE = 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 ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "token_type_ids": token_type_ids, "langs": token_type_ids, "lengths": input_lengths, } return config, inputs_dict @require_tf class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) snake_case__ : Optional[int] = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable snake_case__ : Union[str, Any] = ( { "feature-extraction": TFFlaubertModel, "fill-mask": TFFlaubertWithLMHeadModel, "question-answering": TFFlaubertForQuestionAnsweringSimple, "text-classification": TFFlaubertForSequenceClassification, "token-classification": TFFlaubertForTokenClassification, "zero-shot": TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) snake_case__ : Union[str, Any] = False snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Tuple: if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast" ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = TFFlaubertModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , emb_dim=3_7 ) def UpperCAmelCase_ ( self : Optional[int] ) -> Any: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = TFFlaubertModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = TFFlaubertModel.from_pretrained("jplu/tf-flaubert-small-cased" ) __SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [[0, 1_5_8, 7_3_5, 2_5_9_2, 1_4_2_4, 6_7_2_7, 8_2, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = tf.TensorShape((1, 8, 5_1_2) ) self.assertEqual(output.shape , UpperCAmelCase__ ) # compare the actual values for a slice. __SCREAMING_SNAKE_CASE = tf.convert_to_tensor( [ [ [-1.8_768_773, -1.566_555, 0.27_072_418], [-1.6_920_038, -0.5_873_505, 1.9_329_599], [-2.9_563_985, -1.6_993_835, 1.7_972_052], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" import pytest import datasets # Import fixture modules as plugins a__ : Union[str, Any] = ['''tests.fixtures.files''', '''tests.fixtures.hub''', '''tests.fixtures.fsspec'''] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' for item in items: if any(marker in item.keywords for marker in ["integration", "unit"] ): continue item.add_marker(pytest.mark.unit ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' config.addinivalue_line("markers" , "torchaudio_latest: mark test to run with torchaudio>=0.12" ) @pytest.fixture(autouse=lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tmp_path_factory.getbasetemp() / "cache" __SCREAMING_SNAKE_CASE = test_hf_cache_home / "datasets" __SCREAMING_SNAKE_CASE = test_hf_cache_home / "metrics" __SCREAMING_SNAKE_CASE = test_hf_cache_home / "modules" monkeypatch.setattr("datasets.config.HF_DATASETS_CACHE" , str(lowerCAmelCase_ ) ) monkeypatch.setattr("datasets.config.HF_METRICS_CACHE" , str(lowerCAmelCase_ ) ) monkeypatch.setattr("datasets.config.HF_MODULES_CACHE" , str(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = test_hf_datasets_cache / "downloads" monkeypatch.setattr("datasets.config.DOWNLOADED_DATASETS_PATH" , str(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = test_hf_datasets_cache / "downloads" / "extracted" monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(lowerCAmelCase_ ) ) @pytest.fixture(autouse=lowerCAmelCase_ , scope="session" ) def UpperCAmelCase__ (): '''simple docstring''' datasets.disable_progress_bar() @pytest.fixture(autouse=lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' monkeypatch.setattr("datasets.config.HF_UPDATE_DOWNLOAD_COUNTS" , lowerCAmelCase_ ) @pytest.fixture def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' monkeypatch.setattr("sqlalchemy.util.deprecations.SILENCE_UBER_WARNING" , lowerCAmelCase_ )
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def UpperCAmelCase_ ( self : List[Any] ) -> str: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""simple docstring""" import unittest from diffusers import FlaxAutoencoderKL from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax from .test_modeling_common_flax import FlaxModelTesterMixin if is_flax_available(): import jax @require_flax class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Optional[int] = FlaxAutoencoderKL @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = jax.random.PRNGKey(0 ) __SCREAMING_SNAKE_CASE = jax.random.uniform(UpperCAmelCase__ , ((batch_size, num_channels) + sizes) ) return {"sample": image, "prng_key": prng_key} def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = { "block_out_channels": [3_2, 6_4], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" from typing import Any class UpperCamelCase_ : """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : Any ) -> Any: __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = None def __repr__( self : Any ) -> str: return F"""Node({self.data})""" class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = None def __iter__( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = self.head while node: yield node.data __SCREAMING_SNAKE_CASE = node.next def __len__( self : Tuple ) -> int: return sum(1 for _ in self ) def __repr__( self : Optional[Any] ) -> str: return "->".join([str(UpperCAmelCase__ ) for item in self] ) def __getitem__( self : Optional[int] , UpperCAmelCase__ : int ) -> Any: if not 0 <= index < len(self ): raise ValueError("list index out of range." ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Any ) -> None: if not 0 <= index < len(self ): raise ValueError("list index out of range." ) __SCREAMING_SNAKE_CASE = self.head for _ in range(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = current.next __SCREAMING_SNAKE_CASE = data def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Any ) -> None: self.insert_nth(len(self ) , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Any ) -> None: self.insert_nth(0 , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any ) -> None: if not 0 <= index <= len(self ): raise IndexError("list index out of range" ) __SCREAMING_SNAKE_CASE = Node(UpperCAmelCase__ ) if self.head is None: __SCREAMING_SNAKE_CASE = new_node elif index == 0: __SCREAMING_SNAKE_CASE = self.head # link new_node to head __SCREAMING_SNAKE_CASE = new_node else: __SCREAMING_SNAKE_CASE = self.head for _ in range(index - 1 ): __SCREAMING_SNAKE_CASE = temp.next __SCREAMING_SNAKE_CASE = temp.next __SCREAMING_SNAKE_CASE = new_node def UpperCAmelCase_ ( self : Any ) -> None: # print every node data print(self ) def UpperCAmelCase_ ( self : str ) -> Any: return self.delete_nth(0 ) def UpperCAmelCase_ ( self : Any ) -> Any: # delete from tail return self.delete_nth(len(self ) - 1 ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : int = 0 ) -> Any: if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("List index out of range." ) __SCREAMING_SNAKE_CASE = self.head # default first node if index == 0: __SCREAMING_SNAKE_CASE = self.head.next else: __SCREAMING_SNAKE_CASE = self.head for _ in range(index - 1 ): __SCREAMING_SNAKE_CASE = temp.next __SCREAMING_SNAKE_CASE = temp.next __SCREAMING_SNAKE_CASE = temp.next.next return delete_node.data def UpperCAmelCase_ ( self : Tuple ) -> bool: return self.head is None def UpperCAmelCase_ ( self : Optional[int] ) -> None: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = self.head while current: # Store the current node's next node. __SCREAMING_SNAKE_CASE = current.next # Make the current node's next point backwards __SCREAMING_SNAKE_CASE = prev # Make the previous node be the current node __SCREAMING_SNAKE_CASE = current # Make the current node the next node (to progress iteration) __SCREAMING_SNAKE_CASE = next_node # Return prev in order to put the head at the end __SCREAMING_SNAKE_CASE = prev def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = LinkedList() assert linked_list.is_empty() is True assert str(lowerCAmelCase_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(lowerCAmelCase_ ) == i linked_list.insert_nth(lowerCAmelCase_ , i + 1 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(lowerCAmelCase_ ) == 9 assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): __SCREAMING_SNAKE_CASE = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(-8 , 1 ) ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = [ -9, 100, Node(7734_5112 ), "dlrow olleH", 7, 5555, 0, -192.55555, "Hello, world!", 77.9, Node(10 ), None, None, 12.20, ] __SCREAMING_SNAKE_CASE = LinkedList() for i in test_input: linked_list.insert_tail(lowerCAmelCase_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(lowerCAmelCase_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head __SCREAMING_SNAKE_CASE = linked_list.delete_head() assert result == -9 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail __SCREAMING_SNAKE_CASE = linked_list.delete_tail() assert result == 12.2 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list __SCREAMING_SNAKE_CASE = linked_list.delete_nth(10 ) assert result is None assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!" ) ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(lowerCAmelCase_ ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(lowerCAmelCase_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def UpperCAmelCase__ (): '''simple docstring''' from doctest import testmod testmod() __SCREAMING_SNAKE_CASE = LinkedList() linked_list.insert_head(input("Inserting 1st at head " ).strip() ) linked_list.insert_head(input("Inserting 2nd at head " ).strip() ) print("\nPrint list:" ) linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail " ).strip() ) linked_list.insert_tail(input("Inserting 2nd at tail " ).strip() ) print("\nPrint list:" ) linked_list.print_list() print("\nDelete head" ) linked_list.delete_head() print("Delete tail" ) linked_list.delete_tail() print("\nPrint list:" ) linked_list.print_list() print("\nReverse linked list" ) linked_list.reverse() print("\nPrint list:" ) linked_list.print_list() print("\nString representation of linked list:" ) print(lowerCAmelCase_ ) print("\nReading/changing Node data using indexing:" ) print(f"""Element at Position 1: {linked_list[1]}""" ) __SCREAMING_SNAKE_CASE = input("Enter New Value: " ).strip() print("New list:" ) print(lowerCAmelCase_ ) print(f"""length of linked_list is : {len(lowerCAmelCase_ )}""" ) if __name__ == "__main__": main()
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, 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) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ ) 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(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * num_epochs) , ) # 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import _LazyModule a__ : int = {'''tokenization_byt5''': ['''ByT5Tokenizer''']} if TYPE_CHECKING: from .tokenization_byta import ByTaTokenizer else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() a__ : Union[str, Any] = logging.get_logger('''transformers.models.encodec''') a__ : int = { '''quantizer.vq.layers.*._codebook.inited''': '''quantizer.layers.*.codebook.inited''', '''quantizer.vq.layers.*._codebook.cluster_size''': '''quantizer.layers.*.codebook.cluster_size''', '''quantizer.vq.layers.*._codebook.embed''': '''quantizer.layers.*.codebook.embed''', '''quantizer.vq.layers.*._codebook.embed_avg''': '''quantizer.layers.*.codebook.embed_avg''', } a__ : Any = { '''encoder.model.0.conv.conv''': '''encoder.layers.0.conv''', '''encoder.model.1.block.1.conv.conv''': '''encoder.layers.1.block.1.conv''', '''encoder.model.1.block.3.conv.conv''': '''encoder.layers.1.block.3.conv''', '''encoder.model.1.shortcut.conv.conv''': '''encoder.layers.1.shortcut.conv''', '''encoder.model.3.conv.conv''': '''encoder.layers.3.conv''', '''encoder.model.4.block.1.conv.conv''': '''encoder.layers.4.block.1.conv''', '''encoder.model.4.block.3.conv.conv''': '''encoder.layers.4.block.3.conv''', '''encoder.model.4.shortcut.conv.conv''': '''encoder.layers.4.shortcut.conv''', '''encoder.model.6.conv.conv''': '''encoder.layers.6.conv''', '''encoder.model.7.block.1.conv.conv''': '''encoder.layers.7.block.1.conv''', '''encoder.model.7.block.3.conv.conv''': '''encoder.layers.7.block.3.conv''', '''encoder.model.7.shortcut.conv.conv''': '''encoder.layers.7.shortcut.conv''', '''encoder.model.9.conv.conv''': '''encoder.layers.9.conv''', '''encoder.model.10.block.1.conv.conv''': '''encoder.layers.10.block.1.conv''', '''encoder.model.10.block.3.conv.conv''': '''encoder.layers.10.block.3.conv''', '''encoder.model.10.shortcut.conv.conv''': '''encoder.layers.10.shortcut.conv''', '''encoder.model.12.conv.conv''': '''encoder.layers.12.conv''', '''encoder.model.13.lstm''': '''encoder.layers.13.lstm''', '''encoder.model.15.conv.conv''': '''encoder.layers.15.conv''', } a__ : Any = { '''encoder.model.0.conv.norm''': '''encoder.layers.0.norm''', '''encoder.model.1.block.1.conv.norm''': '''encoder.layers.1.block.1.norm''', '''encoder.model.1.block.3.conv.norm''': '''encoder.layers.1.block.3.norm''', '''encoder.model.1.shortcut.conv.norm''': '''encoder.layers.1.shortcut.norm''', '''encoder.model.3.conv.norm''': '''encoder.layers.3.norm''', '''encoder.model.4.block.1.conv.norm''': '''encoder.layers.4.block.1.norm''', '''encoder.model.4.block.3.conv.norm''': '''encoder.layers.4.block.3.norm''', '''encoder.model.4.shortcut.conv.norm''': '''encoder.layers.4.shortcut.norm''', '''encoder.model.6.conv.norm''': '''encoder.layers.6.norm''', '''encoder.model.7.block.1.conv.norm''': '''encoder.layers.7.block.1.norm''', '''encoder.model.7.block.3.conv.norm''': '''encoder.layers.7.block.3.norm''', '''encoder.model.7.shortcut.conv.norm''': '''encoder.layers.7.shortcut.norm''', '''encoder.model.9.conv.norm''': '''encoder.layers.9.norm''', '''encoder.model.10.block.1.conv.norm''': '''encoder.layers.10.block.1.norm''', '''encoder.model.10.block.3.conv.norm''': '''encoder.layers.10.block.3.norm''', '''encoder.model.10.shortcut.conv.norm''': '''encoder.layers.10.shortcut.norm''', '''encoder.model.12.conv.norm''': '''encoder.layers.12.norm''', '''encoder.model.15.conv.norm''': '''encoder.layers.15.norm''', } a__ : List[str] = { '''decoder.model.0.conv.conv''': '''decoder.layers.0.conv''', '''decoder.model.1.lstm''': '''decoder.layers.1.lstm''', '''decoder.model.3.convtr.convtr''': '''decoder.layers.3.conv''', '''decoder.model.4.block.1.conv.conv''': '''decoder.layers.4.block.1.conv''', '''decoder.model.4.block.3.conv.conv''': '''decoder.layers.4.block.3.conv''', '''decoder.model.4.shortcut.conv.conv''': '''decoder.layers.4.shortcut.conv''', '''decoder.model.6.convtr.convtr''': '''decoder.layers.6.conv''', '''decoder.model.7.block.1.conv.conv''': '''decoder.layers.7.block.1.conv''', '''decoder.model.7.block.3.conv.conv''': '''decoder.layers.7.block.3.conv''', '''decoder.model.7.shortcut.conv.conv''': '''decoder.layers.7.shortcut.conv''', '''decoder.model.9.convtr.convtr''': '''decoder.layers.9.conv''', '''decoder.model.10.block.1.conv.conv''': '''decoder.layers.10.block.1.conv''', '''decoder.model.10.block.3.conv.conv''': '''decoder.layers.10.block.3.conv''', '''decoder.model.10.shortcut.conv.conv''': '''decoder.layers.10.shortcut.conv''', '''decoder.model.12.convtr.convtr''': '''decoder.layers.12.conv''', '''decoder.model.13.block.1.conv.conv''': '''decoder.layers.13.block.1.conv''', '''decoder.model.13.block.3.conv.conv''': '''decoder.layers.13.block.3.conv''', '''decoder.model.13.shortcut.conv.conv''': '''decoder.layers.13.shortcut.conv''', '''decoder.model.15.conv.conv''': '''decoder.layers.15.conv''', } a__ : str = { '''decoder.model.0.conv.norm''': '''decoder.layers.0.norm''', '''decoder.model.3.convtr.norm''': '''decoder.layers.3.norm''', '''decoder.model.4.block.1.conv.norm''': '''decoder.layers.4.block.1.norm''', '''decoder.model.4.block.3.conv.norm''': '''decoder.layers.4.block.3.norm''', '''decoder.model.4.shortcut.conv.norm''': '''decoder.layers.4.shortcut.norm''', '''decoder.model.6.convtr.norm''': '''decoder.layers.6.norm''', '''decoder.model.7.block.1.conv.norm''': '''decoder.layers.7.block.1.norm''', '''decoder.model.7.block.3.conv.norm''': '''decoder.layers.7.block.3.norm''', '''decoder.model.7.shortcut.conv.norm''': '''decoder.layers.7.shortcut.norm''', '''decoder.model.9.convtr.norm''': '''decoder.layers.9.norm''', '''decoder.model.10.block.1.conv.norm''': '''decoder.layers.10.block.1.norm''', '''decoder.model.10.block.3.conv.norm''': '''decoder.layers.10.block.3.norm''', '''decoder.model.10.shortcut.conv.norm''': '''decoder.layers.10.shortcut.norm''', '''decoder.model.12.convtr.norm''': '''decoder.layers.12.norm''', '''decoder.model.13.block.1.conv.norm''': '''decoder.layers.13.block.1.norm''', '''decoder.model.13.block.3.conv.norm''': '''decoder.layers.13.block.3.norm''', '''decoder.model.13.shortcut.conv.norm''': '''decoder.layers.13.shortcut.norm''', '''decoder.model.15.conv.norm''': '''decoder.layers.15.norm''', } a__ : Dict = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } a__ : Optional[Any] = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } a__ : Any = [] a__ : List[str] = [] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' for attribute in key.split("." ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) if weight_type is not None: __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ).shape else: __SCREAMING_SNAKE_CASE = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": __SCREAMING_SNAKE_CASE = value elif weight_type == "weight_g": __SCREAMING_SNAKE_CASE = value elif weight_type == "weight_v": __SCREAMING_SNAKE_CASE = value elif weight_type == "bias": __SCREAMING_SNAKE_CASE = value elif weight_type == "running_mean": __SCREAMING_SNAKE_CASE = value elif weight_type == "running_var": __SCREAMING_SNAKE_CASE = value elif weight_type == "num_batches_tracked": __SCREAMING_SNAKE_CASE = value elif weight_type == "weight_ih_l0": __SCREAMING_SNAKE_CASE = value elif weight_type == "weight_hh_l0": __SCREAMING_SNAKE_CASE = value elif weight_type == "bias_ih_l0": __SCREAMING_SNAKE_CASE = value elif weight_type == "bias_hh_l0": __SCREAMING_SNAKE_CASE = value elif weight_type == "weight_ih_l1": __SCREAMING_SNAKE_CASE = value elif weight_type == "weight_hh_l1": __SCREAMING_SNAKE_CASE = value elif weight_type == "bias_ih_l1": __SCREAMING_SNAKE_CASE = value elif weight_type == "bias_hh_l1": __SCREAMING_SNAKE_CASE = value else: __SCREAMING_SNAKE_CASE = value logger.info(f"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' for key in ignore_keys: if key.endswith(".*" ): if name.startswith(key[:-1] ): return True elif ".*." in key: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = key.split(".*." ) if prefix in name and suffix in name: return True elif key in name: return True return False def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] if model_name == "encodec_24khz" or "encodec_32khz": __SCREAMING_SNAKE_CASE = MAPPING_24K elif model_name == "encodec_48khz": __SCREAMING_SNAKE_CASE = MAPPING_48K else: raise ValueError(f"""Unsupported model: {model_name}""" ) for name, value in orig_dict.items(): if should_ignore(lowerCAmelCase_ , lowerCAmelCase_ ): logger.info(f"""{name} was ignored""" ) continue __SCREAMING_SNAKE_CASE = False for key, mapped_key in MAPPING.items(): if "*" in key: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = key.split(".*." ) if prefix in name and suffix in name: __SCREAMING_SNAKE_CASE = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith("embed" ) and name.endswith("embed_avg" ): continue __SCREAMING_SNAKE_CASE = True if "*" in mapped_key: __SCREAMING_SNAKE_CASE = name.split(lowerCAmelCase_ )[0].split("." )[-2] __SCREAMING_SNAKE_CASE = mapped_key.replace("*" , lowerCAmelCase_ ) if "weight_g" in name: __SCREAMING_SNAKE_CASE = "weight_g" elif "weight_v" in name: __SCREAMING_SNAKE_CASE = "weight_v" elif "weight_ih_l0" in name: __SCREAMING_SNAKE_CASE = "weight_ih_l0" elif "weight_hh_l0" in name: __SCREAMING_SNAKE_CASE = "weight_hh_l0" elif "bias_ih_l0" in name: __SCREAMING_SNAKE_CASE = "bias_ih_l0" elif "bias_hh_l0" in name: __SCREAMING_SNAKE_CASE = "bias_hh_l0" elif "weight_ih_l1" in name: __SCREAMING_SNAKE_CASE = "weight_ih_l1" elif "weight_hh_l1" in name: __SCREAMING_SNAKE_CASE = "weight_hh_l1" elif "bias_ih_l1" in name: __SCREAMING_SNAKE_CASE = "bias_ih_l1" elif "bias_hh_l1" in name: __SCREAMING_SNAKE_CASE = "bias_hh_l1" elif "bias" in name: __SCREAMING_SNAKE_CASE = "bias" elif "weight" in name: __SCREAMING_SNAKE_CASE = "weight" elif "running_mean" in name: __SCREAMING_SNAKE_CASE = "running_mean" elif "running_var" in name: __SCREAMING_SNAKE_CASE = "running_var" elif "num_batches_tracked" in name: __SCREAMING_SNAKE_CASE = "num_batches_tracked" else: __SCREAMING_SNAKE_CASE = None set_recursively(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) continue if not is_used: unused_weights.append(lowerCAmelCase_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if config_path is not None: __SCREAMING_SNAKE_CASE = EncodecConfig.from_pretrained(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": __SCREAMING_SNAKE_CASE = [8, 5, 4, 4] __SCREAMING_SNAKE_CASE = [2.2] __SCREAMING_SNAKE_CASE = 64 __SCREAMING_SNAKE_CASE = 3_2000 __SCREAMING_SNAKE_CASE = 2048 __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False elif model_name == "encodec_48khz": __SCREAMING_SNAKE_CASE = [8, 5, 4, 2] __SCREAMING_SNAKE_CASE = [3.0, 6.0, 12.0, 24.0] __SCREAMING_SNAKE_CASE = 4_8000 __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = "time_group_norm" __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = 1.0 __SCREAMING_SNAKE_CASE = 0.01 else: raise ValueError(f"""Unknown model name: {model_name}""" ) __SCREAMING_SNAKE_CASE = EncodecModel(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights __SCREAMING_SNAKE_CASE = original_checkpoint["best_state"] recursively_load_weights(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if repo_id: print("Pushing to the hub..." ) feature_extractor.push_to_hub(lowerCAmelCase_ ) model.push_to_hub(lowerCAmelCase_ ) if __name__ == "__main__": a__ : int = argparse.ArgumentParser() parser.add_argument( '''--model''', default='''encodec_24khz''', type=str, help='''The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) a__ : str = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 50 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F"{solution() = }")
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ASTConfig from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_torchaudio_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ASTForAudioClassification, ASTModel from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) if is_torchaudio_available(): import torchaudio from transformers import ASTFeatureExtractor class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str=1_3 , UpperCAmelCase__ : List[str]=2 , UpperCAmelCase__ : Dict=2_4 , UpperCAmelCase__ : Optional[int]=1_6 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Optional[Any]=3_2 , UpperCAmelCase__ : str=5 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : str=3_7 , UpperCAmelCase__ : str="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[Any]=1_0 , UpperCAmelCase__ : str=0.02 , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : Optional[Any]=2 , ) -> str: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = num_mel_bins __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = frequency_stride __SCREAMING_SNAKE_CASE = time_stride # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) __SCREAMING_SNAKE_CASE = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1 __SCREAMING_SNAKE_CASE = (self.max_length - self.patch_size) // self.time_stride + 1 __SCREAMING_SNAKE_CASE = frequency_out_dimension * time_out_dimension __SCREAMING_SNAKE_CASE = num_patches + 2 def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_values, labels def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return ASTConfig( patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple ) -> Any: __SCREAMING_SNAKE_CASE = ASTModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_values": input_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( ( ASTModel, ASTForAudioClassification, ) if is_torch_available() else () ) snake_case__ : List[Any] = ( {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel} if is_torch_available() else {} ) snake_case__ : Optional[int] = False snake_case__ : List[str] = False snake_case__ : str = False snake_case__ : List[str] = False def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] ) -> Optional[int]: if pipeline_test_casse_name == "AudioClassificationPipelineTests": return True return False def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = ASTModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="AST does not use inputs_embeds" ) def UpperCAmelCase_ ( self : List[str] ) -> int: pass def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["input_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Dict ) -> str: for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = ASTModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = hf_hub_download( repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = torchaudio.load(lowerCAmelCase_ ) return audio, sampling_rate @require_torch @require_torchaudio class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @cached_property def UpperCAmelCase_ ( self : List[str] ) -> int: return ( ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ) if is_torchaudio_available() else None ) @slow def UpperCAmelCase_ ( self : str ) -> Tuple: __SCREAMING_SNAKE_CASE = self.default_feature_extractor __SCREAMING_SNAKE_CASE = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.default_feature_extractor __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = prepare_audio() __SCREAMING_SNAKE_CASE = audio.squeeze().numpy() __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , sampling_rate=UpperCAmelCase__ , return_tensors="pt" ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 5_2_7) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([-0.8_760, -7.0_042, -8.6_602] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) )
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def UpperCAmelCase_ ( self : List[Any] ) -> str: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCamelCase_ : """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Optional[Any]=4 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : Tuple=7 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : List[Any]=9_9 , UpperCAmelCase__ : Union[str, Any]=3_6 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[str]=3_7 , UpperCAmelCase__ : Optional[int]="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : str=5_1_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : List[str]=6 , UpperCAmelCase__ : Optional[int]=6 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : List[str]=1_0_0_0 , ) -> Dict: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = coordinate_size __SCREAMING_SNAKE_CASE = shape_size __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __SCREAMING_SNAKE_CASE = text_seq_length __SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 + 1 __SCREAMING_SNAKE_CASE = self.text_seq_length + self.image_seq_length def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __SCREAMING_SNAKE_CASE = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __SCREAMING_SNAKE_CASE = bbox[i, j, 3] __SCREAMING_SNAKE_CASE = bbox[i, j, 1] __SCREAMING_SNAKE_CASE = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __SCREAMING_SNAKE_CASE = bbox[i, j, 2] __SCREAMING_SNAKE_CASE = bbox[i, j, 0] __SCREAMING_SNAKE_CASE = tmp_coordinate __SCREAMING_SNAKE_CASE = tf.constant(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.text_seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = TFLayoutLMvaModel(config=UpperCAmelCase__ ) # text + image __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , training=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , training=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , training=UpperCAmelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __SCREAMING_SNAKE_CASE = model({"pixel_values": pixel_values} , training=UpperCAmelCase__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : str ) -> str: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = TFLayoutLMvaForSequenceClassification(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , training=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = TFLayoutLMvaForTokenClassification(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , training=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = 2 __SCREAMING_SNAKE_CASE = TFLayoutLMvaForQuestionAnswering(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , training=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 UpperCAmelCase_ ( self : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = 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) , (__SCREAMING_SNAKE_CASE)) = config_and_inputs __SCREAMING_SNAKE_CASE = { "input_ids": input_ids, "bbox": bbox, "pixel_values": pixel_values, "token_type_ids": token_type_ids, "attention_mask": input_mask, } return config, inputs_dict @require_tf class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) snake_case__ : Optional[Any] = ( {"document-question-answering": TFLayoutLMvaForQuestionAnswering, "feature-extraction": TFLayoutLMvaModel} if is_tf_available() else {} ) snake_case__ : Union[str, Any] = False snake_case__ : int = False snake_case__ : str = False def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str ) -> Optional[Any]: return True def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str=False ) -> dict: __SCREAMING_SNAKE_CASE = copy.deepcopy(UpperCAmelCase__ ) if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = { k: tf.tile(tf.expand_dims(UpperCAmelCase__ , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(UpperCAmelCase__ , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __SCREAMING_SNAKE_CASE = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = TFLayoutLMvaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Any ) -> List[str]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) if getattr(UpperCAmelCase__ , "hf_compute_loss" , UpperCAmelCase__ ): # The number of elements in the loss should be the same as the number of elements in the label __SCREAMING_SNAKE_CASE = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=UpperCAmelCase__ )[0] ] __SCREAMING_SNAKE_CASE = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __SCREAMING_SNAKE_CASE = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = prepared_for_class.pop("input_ids" ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , **UpperCAmelCase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __SCREAMING_SNAKE_CASE = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = prepared_for_class.pop("input_ids" ) if "labels" in prepared_for_class: __SCREAMING_SNAKE_CASE = prepared_for_class["labels"].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __SCREAMING_SNAKE_CASE = -1_0_0 __SCREAMING_SNAKE_CASE = tf.convert_to_tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , **UpperCAmelCase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __SCREAMING_SNAKE_CASE = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __SCREAMING_SNAKE_CASE = self._prepare_for_class(inputs_dict.copy() , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) # Get keys that were added with the _prepare_for_class function __SCREAMING_SNAKE_CASE = prepared_for_class.keys() - inputs_dict.keys() __SCREAMING_SNAKE_CASE = inspect.signature(model.call ).parameters __SCREAMING_SNAKE_CASE = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __SCREAMING_SNAKE_CASE = {0: "input_ids"} for label_key in label_keys: __SCREAMING_SNAKE_CASE = signature_names.index(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = label_key __SCREAMING_SNAKE_CASE = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __SCREAMING_SNAKE_CASE = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __SCREAMING_SNAKE_CASE = prepared_for_class[value] __SCREAMING_SNAKE_CASE = tuple(UpperCAmelCase__ ) # Send to model __SCREAMING_SNAKE_CASE = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def UpperCAmelCase_ ( self : Optional[int] ) -> List[str]: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[Any]: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Any ) -> Dict: for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = TFLayoutLMvaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @cached_property def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: return LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) if is_vision_available() else None @slow def UpperCAmelCase_ ( self : Any ) -> Dict: __SCREAMING_SNAKE_CASE = TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base" ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=UpperCAmelCase__ , return_tensors="tf" ).pixel_values __SCREAMING_SNAKE_CASE = tf.constant([[1, 2]] ) __SCREAMING_SNAKE_CASE = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __SCREAMING_SNAKE_CASE = model(input_ids=UpperCAmelCase__ , bbox=UpperCAmelCase__ , pixel_values=UpperCAmelCase__ , training=UpperCAmelCase__ ) # verify the logits __SCREAMING_SNAKE_CASE = (1, 1_9_9, 7_6_8) self.assertEqual(outputs.last_hidden_state.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.constant( [[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) )
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) for i in range(n - 1 ): for j in range(i + 1 , lowerCAmelCase_ ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if len(lowerCAmelCase_ ) <= 1: return arr, 0 __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) // 2 __SCREAMING_SNAKE_CASE = arr[0:mid] __SCREAMING_SNAKE_CASE = arr[mid:] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = count_inversions_recursive(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = count_inversions_recursive(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = _count_cross_inversions(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = inversion_p + inversions_q + cross_inversions return c, num_inversions def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = __SCREAMING_SNAKE_CASE = __SCREAMING_SNAKE_CASE = 0 while i < len(lowerCAmelCase_ ) and j < len(lowerCAmelCase_ ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(lowerCAmelCase_ ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(lowerCAmelCase_ ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) __SCREAMING_SNAKE_CASE = count_inversions_bf(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = count_inversions_recursive(lowerCAmelCase_ ) assert num_inversions_bf == num_inversions_recursive == 8 print("number of inversions = " , lowerCAmelCase_ ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() __SCREAMING_SNAKE_CASE = count_inversions_bf(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = count_inversions_recursive(lowerCAmelCase_ ) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = " , lowerCAmelCase_ ) # an empty list should also have zero inversions __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = count_inversions_bf(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = count_inversions_recursive(lowerCAmelCase_ ) assert num_inversions_bf == num_inversions_recursive == 0 print("number of inversions = " , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' _validate_point(lowerCAmelCase_ ) _validate_point(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(a - b ) for a, b in zip(lowerCAmelCase_ , lowerCAmelCase_ ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if point: if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): for item in point: if not isinstance(lowerCAmelCase_ , (int, float) ): __SCREAMING_SNAKE_CASE = ( "Expected a list of numbers as input, found " f"""{type(lowerCAmelCase_ ).__name__}""" ) raise TypeError(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = f"""Expected a list of numbers as input, found {type(lowerCAmelCase_ ).__name__}""" raise TypeError(lowerCAmelCase_ ) else: raise ValueError("Missing an input" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' _validate_point(lowerCAmelCase_ ) _validate_point(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(x - y ) for x, y in zip(lowerCAmelCase_ , lowerCAmelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] ) __SCREAMING_SNAKE_CASE = get_activation("gelu" ) self.assertTrue(torch.allclose(gelu_python(UpperCAmelCase__ ) , torch_builtin(UpperCAmelCase__ ) ) ) self.assertFalse(torch.allclose(gelu_python(UpperCAmelCase__ ) , gelu_new(UpperCAmelCase__ ) ) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = torch.tensor([-1_0_0, -1, -0.1, 0, 0.1, 1.0, 1_0_0] ) __SCREAMING_SNAKE_CASE = get_activation("gelu" ) __SCREAMING_SNAKE_CASE = get_activation("gelu_10" ) __SCREAMING_SNAKE_CASE = torch_builtin(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = geluaa(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(UpperCAmelCase__ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def UpperCAmelCase_ ( self : str ) -> List[Any]: get_activation("gelu" ) get_activation("gelu_10" ) get_activation("gelu_fast" ) get_activation("gelu_new" ) get_activation("gelu_python" ) get_activation("gelu_pytorch_tanh" ) get_activation("linear" ) get_activation("mish" ) get_activation("quick_gelu" ) get_activation("relu" ) get_activation("sigmoid" ) get_activation("silu" ) get_activation("swish" ) get_activation("tanh" ) with self.assertRaises(UpperCAmelCase__ ): get_activation("bogus" ) with self.assertRaises(UpperCAmelCase__ ): get_activation(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = get_activation("gelu" ) __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = get_activation("gelu" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = acta.a
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class UpperCamelCase_ : """simple docstring""" pass
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) 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 UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=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 UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_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__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.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 UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : Optional[Any]=3 , UpperCAmelCase__ : Optional[int]=1_8 , UpperCAmelCase__ : Optional[Any]=3_0 , UpperCAmelCase__ : Optional[Any]=4_0_0 , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Optional[int]=True , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = size if size is not None else {"height": 1_8, "width": 1_8} __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = min_resolution __SCREAMING_SNAKE_CASE = max_resolution __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = size __SCREAMING_SNAKE_CASE = apply_ocr def UpperCAmelCase_ ( self : str ) -> Tuple: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = LayoutLMvaImageProcessor if is_pytesseract_available() else None def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessingTester(self ) @property def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase_ ( self : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(UpperCAmelCase__ , "do_resize" ) ) self.assertTrue(hasattr(UpperCAmelCase__ , "size" ) ) self.assertTrue(hasattr(UpperCAmelCase__ , "apply_ocr" ) ) def UpperCAmelCase_ ( self : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 1_8, "width": 1_8} ) __SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {"height": 4_2, "width": 4_2} ) def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: pass def UpperCAmelCase_ ( self : str ) -> int: # Initialize image_processing __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) self.assertIsInstance(encoding.words , UpperCAmelCase__ ) self.assertIsInstance(encoding.boxes , UpperCAmelCase__ ) # Test batched __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase_ ( self : str ) -> Tuple: # Initialize image_processing __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , numpify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase_ ( self : Dict ) -> Tuple: # Initialize image_processing __SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE = prepare_image_inputs(self.image_processor_tester , equal_resolution=UpperCAmelCase__ , torchify=UpperCAmelCase__ ) for image in image_inputs: self.assertIsInstance(UpperCAmelCase__ , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) def UpperCAmelCase_ ( self : List[Any] ) -> Dict: # with apply_OCR = True __SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessor() from datasets import load_dataset __SCREAMING_SNAKE_CASE = load_dataset("hf-internal-testing/fixtures_docvqa" , split="test" ) __SCREAMING_SNAKE_CASE = Image.open(ds[0]["file"] ).convert("RGB" ) __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __SCREAMING_SNAKE_CASE = [["11:14", "to", "11:39", "a.m", "11:39", "to", "11:44", "a.m.", "11:44", "a.m.", "to", "12:25", "p.m.", "12:25", "to", "12:58", "p.m.", "12:58", "to", "4:00", "p.m.", "2:00", "to", "5:00", "p.m.", "Coffee", "Break", "Coffee", "will", "be", "served", "for", "men", "and", "women", "in", "the", "lobby", "adjacent", "to", "exhibit", "area.", "Please", "move", "into", "exhibit", "area.", "(Exhibits", "Open)", "TRRF", "GENERAL", "SESSION", "(PART", "|)", "Presiding:", "Lee", "A.", "Waller", "TRRF", "Vice", "President", "“Introductory", "Remarks”", "Lee", "A.", "Waller,", "TRRF", "Vice", "Presi-", "dent", "Individual", "Interviews", "with", "TRRF", "Public", "Board", "Members", "and", "Sci-", "entific", "Advisory", "Council", "Mem-", "bers", "Conducted", "by", "TRRF", "Treasurer", "Philip", "G.", "Kuehn", "to", "get", "answers", "which", "the", "public", "refrigerated", "warehousing", "industry", "is", "looking", "for.", "Plus", "questions", "from", "the", "floor.", "Dr.", "Emil", "M.", "Mrak,", "University", "of", "Cal-", "ifornia,", "Chairman,", "TRRF", "Board;", "Sam", "R.", "Cecil,", "University", "of", "Georgia", "College", "of", "Agriculture;", "Dr.", "Stanley", "Charm,", "Tufts", "University", "School", "of", "Medicine;", "Dr.", "Robert", "H.", "Cotton,", "ITT", "Continental", "Baking", "Company;", "Dr.", "Owen", "Fennema,", "University", "of", "Wis-", "consin;", "Dr.", "Robert", "E.", "Hardenburg,", "USDA.", "Questions", "and", "Answers", "Exhibits", "Open", "Capt.", "Jack", "Stoney", "Room", "TRRF", "Scientific", "Advisory", "Council", "Meeting", "Ballroom", "Foyer"]] # noqa: E231 __SCREAMING_SNAKE_CASE = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , UpperCAmelCase__ ) self.assertListEqual(encoding.boxes , UpperCAmelCase__ ) # with apply_OCR = False __SCREAMING_SNAKE_CASE = LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = image_processing(UpperCAmelCase__ , return_tensors="pt" ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" import argparse import random import joblib import numpy as np import torch from igf.igf import ( SecondaryLearner, collect_objective_set, compute_perplexity, generate_datasets, load_gpta, recopy_gpta, set_seed, train_secondary_learner, ) from torch.utils.data import DataLoader, RandomSampler from transformers import GPTaLMHeadModel def UpperCAmelCase__ (lowerCAmelCase_=32 , lowerCAmelCase_=10 , lowerCAmelCase_=100 , lowerCAmelCase_=1026 , lowerCAmelCase_=True , lowerCAmelCase_="data/tokenized_stories_train_wikitext103.jbl" , lowerCAmelCase_="igf_context_pairs.jbl" , ): '''simple docstring''' set_seed(3 ) # generate train_data and objective_set __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = generate_datasets( lowerCAmelCase_ , lowerCAmelCase_ , number=lowerCAmelCase_ , min_len=1026 , trim=lowerCAmelCase_ ) # keeps model same across runs set_seed(4 ) # model, lm_optimizer, lm_scheduler = recopy_gpt2(model, device, max_steps) # store original model weights # can we train on GPU? __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) # load pretrained model __SCREAMING_SNAKE_CASE = load_gpta("gpt2" ).to(lowerCAmelCase_ ) print("computing perplexity on objective set" ) __SCREAMING_SNAKE_CASE = compute_perplexity(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ).item() print("perplexity on objective set:" , lowerCAmelCase_ ) # collect igf pairs and save to file demo.jbl collect_objective_set(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # clean up, delete model and data we don't need anymore del model, train_data, objective_set torch.cuda.empty_cache() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_=15 , lowerCAmelCase_=128 , lowerCAmelCase_=100 , lowerCAmelCase_="igf_model.pt" , ): '''simple docstring''' set_seed(42 ) # Load pre-trained model __SCREAMING_SNAKE_CASE = GPTaLMHeadModel.from_pretrained("gpt2" ) # Initialize secondary learner to use embedding weights of model __SCREAMING_SNAKE_CASE = SecondaryLearner(lowerCAmelCase_ ) # Train secondary learner __SCREAMING_SNAKE_CASE = train_secondary_learner( lowerCAmelCase_ , lowerCAmelCase_ , max_epochs=lowerCAmelCase_ , batch_size=lowerCAmelCase_ , eval_freq=100 , igf_model_path=lowerCAmelCase_ , ) del model, secondary_learner_train_data torch.cuda.empty_cache() return secondary_learner def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=32 , lowerCAmelCase_=1000 , lowerCAmelCase_=16 , lowerCAmelCase_=1.0 , lowerCAmelCase_=recopy_gpta , lowerCAmelCase_=None , lowerCAmelCase_=10 , lowerCAmelCase_="gpt2_finetuned.pt" , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) __SCREAMING_SNAKE_CASE = RandomSampler(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader(lowerCAmelCase_ , sampler=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max_steps // (len(lowerCAmelCase_ )) + 1 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = torch.zeros((1, context_len) , dtype=torch.long , device=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = recopy_model(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) model.train() if secondary_learner is not None: secondary_learner.to(lowerCAmelCase_ ) secondary_learner.eval() __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] # Compute the performance of the transformer model at the beginning __SCREAMING_SNAKE_CASE = compute_perplexity(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) test_perps.append(lowerCAmelCase_ ) print("Test perplexity, step" , lowerCAmelCase_ , ":" , lowerCAmelCase_ ) for epoch in range(int(lowerCAmelCase_ ) ): for step, example in enumerate(lowerCAmelCase_ ): torch.cuda.empty_cache() __SCREAMING_SNAKE_CASE = random.randint(0 , example.size(2 ) - context_len - 1 ) __SCREAMING_SNAKE_CASE = example[0, 0, start : start + context_len] lm_optimizer.zero_grad() __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ , labels=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = True if secondary_learner is not None: __SCREAMING_SNAKE_CASE = secondary_learner.forward( torch.tensor(lowerCAmelCase_ , dtype=torch.long , device=lowerCAmelCase_ ).unsqueeze(0 ) )[0].item() observed_qs.append(float(lowerCAmelCase_ ) ) # Here we implement the simple non-constant threshold for the predicted IG(X) value # We will decay the selectivity of our secondary learner filter from # 1 standard deviation above average to 1 below average after 10 batches. if global_step == 10: __SCREAMING_SNAKE_CASE = -1 if predicted_q < threshold: __SCREAMING_SNAKE_CASE = False # If we passed the filter, add the context to the batch! if do_backprop: contexts.append(np.array(context.cpu() ) ) __SCREAMING_SNAKE_CASE = outputs[0] lm_loss.backward() examples += 1 del outputs # Once the batch is filled with enough contexts, backprop on the batch. if examples == batch_size: torch.cuda.empty_cache() __SCREAMING_SNAKE_CASE = 0 # Do LM backprop torch.nn.utils.clip_grad_norm_(model.parameters() , 3.0 ) lm_optimizer.step() lm_scheduler.step() # Update learning rate schedule global_step += 1 # Compute the performance of the transformer model at this batch if global_step % eval_interval == 0: __SCREAMING_SNAKE_CASE = compute_perplexity(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) test_perps.append(lowerCAmelCase_ ) print("Test perplexity, step" , lowerCAmelCase_ , ":" , lowerCAmelCase_ ) # Break out of the loop after 60 batches if max_steps > 0 and global_step > 60: break if max_steps > 0 and global_step > 60: break # save finetuned transformer model torch.save(model.state_dict() , lowerCAmelCase_ ) torch.cuda.empty_cache() # Do some cleaning up so we can reinitialize for the next run of this function del lm_optimizer del lm_scheduler return model def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Fine-tune a transformer model with IGF on a language modeling task" ) # Required parameters parser.add_argument( "--data_dir" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="The input data dir. Should contain data files for WikiText." , ) parser.add_argument( "--model_name_or_path" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--data_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help=( "A jbl file containing tokenized data which can be split as objective dataset, " "train_dataset and test_dataset." ) , ) parser.add_argument( "--igf_data_file" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="A jbl file containing the context and information gain pairs to train secondary learner." , ) parser.add_argument( "--output_dir" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="The output directory where the final fine-tuned model is stored." , ) parser.add_argument( "--tokenizer_name" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="Pretrained tokenizer name or path if not the same as model_name" , ) parser.add_argument("--seed" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , help="A seed for reproducible training." ) parser.add_argument( "--context_len" , default=32 , type=lowerCAmelCase_ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--size_objective_set" , default=100 , type=lowerCAmelCase_ , help="number of articles that are long enough to be used as our objective set" , ) parser.add_argument( "--eval_freq" , default=100 , type=lowerCAmelCase_ , help="secondary model evaluation is triggered at eval_freq" ) parser.add_argument("--max_steps" , default=1000 , type=lowerCAmelCase_ , help="To calculate training epochs" ) parser.add_argument( "--secondary_learner_batch_size" , default=128 , type=lowerCAmelCase_ , help="batch size of training data for secondary learner" , ) parser.add_argument( "--batch_size" , default=16 , type=lowerCAmelCase_ , help="batch size of training data of language model(gpt2) " ) parser.add_argument( "--eval_interval" , default=10 , type=lowerCAmelCase_ , help=( "decay the selectivity of our secondary learner filter from" "1 standard deviation above average to 1 below average after 10 batches" ) , ) parser.add_argument( "--number" , default=100 , type=lowerCAmelCase_ , help="The number of examples split to be used as objective_set/test_data" ) parser.add_argument( "--min_len" , default=1026 , type=lowerCAmelCase_ , help="The minimum length of the article to be used as objective set" ) parser.add_argument( "--secondary_learner_max_epochs" , default=15 , type=lowerCAmelCase_ , help="number of epochs to train secondary learner" ) parser.add_argument("--trim" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="truncate the example if it exceeds context length" ) parser.add_argument( "--threshold" , default=1.0 , type=lowerCAmelCase_ , help=( "The threshold value used by secondary learner to filter the train_data and allow only" " informative data as input to the model" ) , ) parser.add_argument("--finetuned_model_name" , default="gpt2_finetuned.pt" , type=lowerCAmelCase_ , help="finetuned_model_name" ) parser.add_argument( "--recopy_model" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="Reset the model to the original pretrained GPT-2 weights after each iteration" , ) # function calls # Collecting *n* pairs of context and information gain(X, IG(X)) for training the secondary learner generate_n_pairs( context_len=32 , max_steps=10 , size_objective_set=100 , min_len=1026 , trim=lowerCAmelCase_ , data_file="data/tokenized_stories_train_wikitext103.jbl" , igf_data_file="igf_context_pairs.jbl" , ) # Load train data for secondary learner __SCREAMING_SNAKE_CASE = joblib.load("data/IGF_values.jbl" ) # Train secondary learner __SCREAMING_SNAKE_CASE = training_secondary_learner( lowerCAmelCase_ , secondary_learner_max_epochs=15 , secondary_learner_batch_size=128 , eval_freq=100 , igf_model_path="igf_model.pt" , ) # load pretrained gpt2 model __SCREAMING_SNAKE_CASE = GPTaLMHeadModel.from_pretrained("gpt2" ) set_seed(42 ) # Generate train and test data to train and evaluate gpt2 model __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = generate_datasets( context_len=32 , file="data/tokenized_stories_train_wikitext103.jbl" , number=100 , min_len=1026 , trim=lowerCAmelCase_ ) # fine-tuning of the gpt2 model using igf (Information Gain Filtration) finetune( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , context_len=32 , max_steps=1000 , batch_size=16 , threshold=1.0 , recopy_model=lowerCAmelCase_ , secondary_learner=lowerCAmelCase_ , eval_interval=10 , finetuned_model_name="gpt2_finetuned.pt" , ) if __name__ == "__main__": main()
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Dict = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = [ '''XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMForMultipleChoice''', '''XLMForQuestionAnswering''', '''XLMForQuestionAnsweringSimple''', '''XLMForSequenceClassification''', '''XLMForTokenClassification''', '''XLMModel''', '''XLMPreTrainedModel''', '''XLMWithLMHeadModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : str = [ '''TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMForMultipleChoice''', '''TFXLMForQuestionAnsweringSimple''', '''TFXLMForSequenceClassification''', '''TFXLMForTokenClassification''', '''TFXLMMainLayer''', '''TFXLMModel''', '''TFXLMPreTrainedModel''', '''TFXLMWithLMHeadModel''', ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys a__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy 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 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple=1_0_2_4 , UpperCAmelCase__ : Dict=1_0_2_4 , UpperCAmelCase__ : int=3.6 ) -> List[str]: __SCREAMING_SNAKE_CASE = tokenizer __SCREAMING_SNAKE_CASE = tokenizer.bos_token_id __SCREAMING_SNAKE_CASE = dataset __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = seq_length * chars_per_token * num_of_sequences def __iter__( self : str ) -> List[Any]: __SCREAMING_SNAKE_CASE = iter(self.dataset ) __SCREAMING_SNAKE_CASE = True while more_examples: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(UpperCAmelCase__ )["content"] ) buffer_len += len(buffer[-1] ) except StopIteration: __SCREAMING_SNAKE_CASE = False break __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , truncation=UpperCAmelCase__ )["input_ids"] __SCREAMING_SNAKE_CASE = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(UpperCAmelCase__ ) , self.seq_length ): __SCREAMING_SNAKE_CASE = all_token_ids[i : i + self.seq_length] if len(UpperCAmelCase__ ) == self.seq_length: yield torch.tensor(UpperCAmelCase__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {"streaming": True} __SCREAMING_SNAKE_CASE = load_dataset(args.dataset_name , split="train" , **lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ConstantLengthDataset(lowerCAmelCase_ , lowerCAmelCase_ , seq_length=args.seq_length ) __SCREAMING_SNAKE_CASE = DataLoader(lowerCAmelCase_ , batch_size=args.batch_size ) return eval_dataloader def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' model.eval() __SCREAMING_SNAKE_CASE = [] for step, batch in enumerate(lowerCAmelCase_ ): with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(lowerCAmelCase_ , labels=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(lowerCAmelCase_ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break __SCREAMING_SNAKE_CASE = torch.mean(torch.cat(lowerCAmelCase_ ) ) try: __SCREAMING_SNAKE_CASE = torch.exp(lowerCAmelCase_ ) except OverflowError: __SCREAMING_SNAKE_CASE = float("inf" ) return loss.item(), perplexity.item() # Setup Accelerator a__ : Tuple = Accelerator() # Parse configuration a__ : Tuple = HfArgumentParser(EvaluationArguments) a__ : Optional[Any] = parser.parse_args() set_seed(args.seed) # Logging a__ : Optional[int] = logging.getLogger(__name__) logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO ) # Load model and tokenizer a__ : Optional[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt) a__ : int = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader a__ : List[Any] = create_dataloader(args) # Prepare everything with our `accelerator`. a__ , a__ : Tuple = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('''Evaluating and saving model after training''') a__ , a__ : Union[str, Any] = evaluate(args) logger.info(F"loss/eval: {eval_loss}, perplexity: {perplexity}")
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "block_out_channels": [3_2, 6_4], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""simple docstring""" from cva import destroyAllWindows, imread, imshow, waitKey def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = img.shape[0], img.shape[1] # converting each pixel's color to its negative for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [255, 255, 255] - img[i][j] return img if __name__ == "__main__": # read original image a__ : str = imread('''image_data/lena.jpg''', 1) # convert to its negative a__ : Any = convert_to_negative(img) # show result image imshow('''negative of original image''', img) waitKey(0) destroyAllWindows()
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = 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 ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a__ : int = logging.get_logger(__name__) a__ : Optional[int] = { '''ut/deta''': '''https://huggingface.co/ut/deta/resolve/main/config.json''', } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "deta" snake_case__ : Union[str, Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Any , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Tuple=9_0_0 , UpperCAmelCase__ : Any=2_0_4_8 , UpperCAmelCase__ : Optional[Any]=6 , UpperCAmelCase__ : Union[str, Any]=2_0_4_8 , UpperCAmelCase__ : Tuple=8 , UpperCAmelCase__ : str=6 , UpperCAmelCase__ : Optional[Any]=1_0_2_4 , UpperCAmelCase__ : Union[str, Any]=8 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]="relu" , UpperCAmelCase__ : Any=2_5_6 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : int=0.0 , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : str=1.0 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : int=False , UpperCAmelCase__ : str="sine" , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : Dict=4 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : List[str]=3_0_0 , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : List[Any]=5 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : List[str]=1 , UpperCAmelCase__ : Tuple=1 , UpperCAmelCase__ : str=5 , UpperCAmelCase__ : Tuple=2 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : List[Any]=0.25 , **UpperCAmelCase__ : Optional[Any] , ) -> List[Any]: if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) __SCREAMING_SNAKE_CASE = CONFIG_MAPPING["resnet"](out_features=["stage2", "stage3", "stage4"] ) else: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = backbone_config.pop("model_type" ) __SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] __SCREAMING_SNAKE_CASE = config_class.from_dict(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = backbone_config __SCREAMING_SNAKE_CASE = num_queries __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = d_model __SCREAMING_SNAKE_CASE = encoder_ffn_dim __SCREAMING_SNAKE_CASE = encoder_layers __SCREAMING_SNAKE_CASE = encoder_attention_heads __SCREAMING_SNAKE_CASE = decoder_ffn_dim __SCREAMING_SNAKE_CASE = decoder_layers __SCREAMING_SNAKE_CASE = decoder_attention_heads __SCREAMING_SNAKE_CASE = dropout __SCREAMING_SNAKE_CASE = attention_dropout __SCREAMING_SNAKE_CASE = activation_dropout __SCREAMING_SNAKE_CASE = activation_function __SCREAMING_SNAKE_CASE = init_std __SCREAMING_SNAKE_CASE = init_xavier_std __SCREAMING_SNAKE_CASE = encoder_layerdrop __SCREAMING_SNAKE_CASE = auxiliary_loss __SCREAMING_SNAKE_CASE = position_embedding_type # deformable attributes __SCREAMING_SNAKE_CASE = num_feature_levels __SCREAMING_SNAKE_CASE = encoder_n_points __SCREAMING_SNAKE_CASE = decoder_n_points __SCREAMING_SNAKE_CASE = two_stage __SCREAMING_SNAKE_CASE = two_stage_num_proposals __SCREAMING_SNAKE_CASE = with_box_refine __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = class_cost __SCREAMING_SNAKE_CASE = bbox_cost __SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients __SCREAMING_SNAKE_CASE = mask_loss_coefficient __SCREAMING_SNAKE_CASE = dice_loss_coefficient __SCREAMING_SNAKE_CASE = bbox_loss_coefficient __SCREAMING_SNAKE_CASE = giou_loss_coefficient __SCREAMING_SNAKE_CASE = eos_coefficient __SCREAMING_SNAKE_CASE = focal_alpha super().__init__(is_encoder_decoder=UpperCAmelCase__ , **UpperCAmelCase__ ) @property def UpperCAmelCase_ ( self : Any ) -> int: return self.encoder_attention_heads @property def UpperCAmelCase_ ( self : Dict ) -> int: return self.d_model def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) __SCREAMING_SNAKE_CASE = self.backbone_config.to_dict() __SCREAMING_SNAKE_CASE = self.__class__.model_type return output
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" import argparse from argparse import Namespace import torch from torch import nn from transformers import XGLMConfig, XGLMForCausalLM def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [ "decoder.version", "decoder.output_projection.weight", "_float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = emb.weight.shape __SCREAMING_SNAKE_CASE = nn.Linear(lowerCAmelCase_ , lowerCAmelCase_ , bias=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location="cpu" ) __SCREAMING_SNAKE_CASE = Namespace(**checkpoint["cfg"]["model"] ) __SCREAMING_SNAKE_CASE = checkpoint["model"] remove_ignore_keys_(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = state_dict["decoder.embed_tokens.weight"].shape[0] __SCREAMING_SNAKE_CASE = {key.replace("decoder" , "model" ): val for key, val in state_dict.items()} __SCREAMING_SNAKE_CASE = XGLMConfig( vocab_size=lowerCAmelCase_ , max_position_embeddings=args.max_target_positions , num_layers=args.decoder_layers , attention_heads=args.decoder_attention_heads , ffn_dim=args.decoder_ffn_embed_dim , d_model=args.decoder_embed_dim , layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="gelu" , scale_embedding=not args.no_scale_embedding , tie_word_embeddings=args.share_decoder_input_output_embed , ) __SCREAMING_SNAKE_CASE = XGLMForCausalLM(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.embed_tokens ) return model if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument('''fairseq_path''', type=str, help='''path to a model.pt on local filesystem.''') parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') a__ : Dict = parser.parse_args() a__ : List[Any] = convert_fairseq_xglm_checkpoint_from_disk(args.fairseq_path) model.save_pretrained(args.pytorch_dump_folder_path)
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize("keep_in_memory" , [False, True] ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tmp_path / "cache" __SCREAMING_SNAKE_CASE = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): __SCREAMING_SNAKE_CASE = SqlDatasetReader( "dataset" , "sqlite:///" + sqlite_path , cache_dir=lowerCAmelCase_ , keep_in_memory=lowerCAmelCase_ ).read() _check_sql_dataset(lowerCAmelCase_ , lowerCAmelCase_ ) @require_sqlalchemy @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tmp_path / "cache" __SCREAMING_SNAKE_CASE = {"col_1": "string", "col_2": "int64", "col_3": "float64"} __SCREAMING_SNAKE_CASE = features.copy() if features else default_expected_features __SCREAMING_SNAKE_CASE = ( Features({feature: Value(lowerCAmelCase_ ) for feature, dtype in features.items()} ) if features is not None else None ) __SCREAMING_SNAKE_CASE = SqlDatasetReader("dataset" , "sqlite:///" + sqlite_path , features=lowerCAmelCase_ , cache_dir=lowerCAmelCase_ ).read() _check_sql_dataset(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' with contextlib.closing(sqlitea.connect(lowerCAmelCase_ ) ) as con: __SCREAMING_SNAKE_CASE = con.cursor() cur.execute("SELECT * FROM dataset" ) for row in cur: yield row @require_sqlalchemy def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tmp_path / "cache" __SCREAMING_SNAKE_CASE = os.path.join(lowerCAmelCase_ , "tmp.sql" ) __SCREAMING_SNAKE_CASE = SqlDatasetReader("dataset" , "sqlite:///" + sqlite_path , cache_dir=lowerCAmelCase_ ).read() SqlDatasetWriter(lowerCAmelCase_ , "dataset" , "sqlite:///" + output_sqlite_path , num_proc=1 ).write() __SCREAMING_SNAKE_CASE = iter_sql_file(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = iter_sql_file(lowerCAmelCase_ ) for rowa, rowa in zip(lowerCAmelCase_ , lowerCAmelCase_ ): assert rowa == rowa @require_sqlalchemy def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tmp_path / "cache" __SCREAMING_SNAKE_CASE = os.path.join(lowerCAmelCase_ , "tmp.sql" ) __SCREAMING_SNAKE_CASE = SqlDatasetReader("dataset" , "sqlite:///" + sqlite_path , cache_dir=lowerCAmelCase_ ).read() SqlDatasetWriter(lowerCAmelCase_ , "dataset" , "sqlite:///" + output_sqlite_path , num_proc=2 ).write() __SCREAMING_SNAKE_CASE = iter_sql_file(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = iter_sql_file(lowerCAmelCase_ ) for rowa, rowa in zip(lowerCAmelCase_ , lowerCAmelCase_ ): assert rowa == rowa @require_sqlalchemy def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = tmp_path / "cache" __SCREAMING_SNAKE_CASE = os.path.join(lowerCAmelCase_ , "tmp.sql" ) __SCREAMING_SNAKE_CASE = SqlDatasetReader("dataset" , "sqlite:///" + sqlite_path , cache_dir=lowerCAmelCase_ ).read() with pytest.raises(lowerCAmelCase_ ): SqlDatasetWriter(lowerCAmelCase_ , "dataset" , "sqlite:///" + output_sqlite_path , num_proc=0 ).write()
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @property def UpperCAmelCase_ ( self : int ) -> Any: torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDModel( block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def UpperCAmelCase_ ( self : Dict ) -> Tuple: __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pndm.to(UpperCAmelCase__ ) pndm.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=UpperCAmelCase__ , num_inference_steps=2_0 , output_type="numpy" ).images __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=UpperCAmelCase__ , num_inference_steps=2_0 , output_type="numpy" , return_dict=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "google/ddpm-cifar10-32" __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = PNDMScheduler() __SCREAMING_SNAKE_CASE = PNDMPipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pndm.to(UpperCAmelCase__ ) pndm.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pndm(generator=UpperCAmelCase__ , output_type="numpy" ).images __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE = np.array([0.1_564, 0.14_645, 0.1_406, 0.14_715, 0.12_425, 0.14_045, 0.13_115, 0.12_175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""simple docstring""" a__ : Any = { '''A''': '''.-''', '''B''': '''-...''', '''C''': '''-.-.''', '''D''': '''-..''', '''E''': '''.''', '''F''': '''..-.''', '''G''': '''--.''', '''H''': '''....''', '''I''': '''..''', '''J''': '''.---''', '''K''': '''-.-''', '''L''': '''.-..''', '''M''': '''--''', '''N''': '''-.''', '''O''': '''---''', '''P''': '''.--.''', '''Q''': '''--.-''', '''R''': '''.-.''', '''S''': '''...''', '''T''': '''-''', '''U''': '''..-''', '''V''': '''...-''', '''W''': '''.--''', '''X''': '''-..-''', '''Y''': '''-.--''', '''Z''': '''--..''', '''1''': '''.----''', '''2''': '''..---''', '''3''': '''...--''', '''4''': '''....-''', '''5''': '''.....''', '''6''': '''-....''', '''7''': '''--...''', '''8''': '''---..''', '''9''': '''----.''', '''0''': '''-----''', '''&''': '''.-...''', '''@''': '''.--.-.''', ''':''': '''---...''', ''',''': '''--..--''', '''.''': '''.-.-.-''', '''\'''': '''.----.''', '''"''': '''.-..-.''', '''?''': '''..--..''', '''/''': '''-..-.''', '''=''': '''-...-''', '''+''': '''.-.-.''', '''-''': '''-....-''', '''(''': '''-.--.''', ''')''': '''-.--.-''', '''!''': '''-.-.--''', ''' ''': '''/''' } # Exclamation mark is not in ITU-R recommendation # fmt: on a__ : List[Any] = {value: key for key, value in MORSE_CODE_DICT.items()} def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join(REVERSE_DICT[char] for char in message.split() ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = "Morse code here!" print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = encrypt(lowerCAmelCase_ ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = decrypt(lowerCAmelCase_ ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" a__ : Optional[Any] = [ [0, 1_6, 1_3, 0, 0, 0], [0, 0, 1_0, 1_2, 0, 0], [0, 4, 0, 0, 1_4, 0], [0, 0, 9, 0, 0, 2_0], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [False] * len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [s] __SCREAMING_SNAKE_CASE = True while queue: __SCREAMING_SNAKE_CASE = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = u return visited[t] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [-1] * (len(lowerCAmelCase_ )) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [i[:] for i in graph] # Record original cut, copy. while bfs(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = float("Inf" ) __SCREAMING_SNAKE_CASE = sink while s != source: # Find the minimum value in select path __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , graph[parent[s]][s] ) __SCREAMING_SNAKE_CASE = parent[s] max_flow += path_flow __SCREAMING_SNAKE_CASE = sink while v != source: __SCREAMING_SNAKE_CASE = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow __SCREAMING_SNAKE_CASE = parent[v] for i in range(len(lowerCAmelCase_ ) ): for j in range(len(graph[0] ) ): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j) ) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, 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) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=lowerCAmelCase_ , max_length=lowerCAmelCase_ ) 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(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(lowerCAmelCase_ ): # On TPU it's best to pad everything to the same length or training will be very slow. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * num_epochs) , ) # 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if nth_term == "": return [""] __SCREAMING_SNAKE_CASE = int(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = int(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for temp in range(int(lowerCAmelCase_ ) ): series.append(f"""1 / {pow(temp + 1 , int(lowerCAmelCase_ ) )}""" if series else "1" ) return series if __name__ == "__main__": import doctest doctest.testmod() a__ : List[str] = int(input('''Enter the last number (nth term) of the P-Series''')) a__ : Dict = int(input('''Enter the power for P-Series''')) print('''Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p''') print(p_series(nth_term, power))
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging a__ : int = logging.get_logger(__name__) a__ : Tuple = { '''EleutherAI/gpt-j-6B''': '''https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json''', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] = "gptj" snake_case__ : List[Any] = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Any , UpperCAmelCase__ : Dict=5_0_4_0_0 , UpperCAmelCase__ : Union[str, Any]=2_0_4_8 , UpperCAmelCase__ : Dict=4_0_9_6 , UpperCAmelCase__ : str=2_8 , UpperCAmelCase__ : Dict=1_6 , UpperCAmelCase__ : Optional[int]=6_4 , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : int="gelu_new" , UpperCAmelCase__ : Optional[Any]=0.0 , UpperCAmelCase__ : Any=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : List[Any]=1E-5 , UpperCAmelCase__ : Optional[Any]=0.02 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Union[str, Any]=5_0_2_5_6 , UpperCAmelCase__ : List[Any]=5_0_2_5_6 , UpperCAmelCase__ : List[Any]=False , **UpperCAmelCase__ : Tuple , ) -> str: __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = n_positions __SCREAMING_SNAKE_CASE = n_embd __SCREAMING_SNAKE_CASE = n_layer __SCREAMING_SNAKE_CASE = n_head __SCREAMING_SNAKE_CASE = n_inner __SCREAMING_SNAKE_CASE = rotary_dim __SCREAMING_SNAKE_CASE = activation_function __SCREAMING_SNAKE_CASE = resid_pdrop __SCREAMING_SNAKE_CASE = embd_pdrop __SCREAMING_SNAKE_CASE = attn_pdrop __SCREAMING_SNAKE_CASE = layer_norm_epsilon __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = eos_token_id super().__init__( bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , tie_word_embeddings=UpperCAmelCase__ , **UpperCAmelCase__ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : PretrainedConfig , UpperCAmelCase__ : str = "default" , UpperCAmelCase__ : List[PatchingSpec] = None , UpperCAmelCase__ : bool = False , ) -> Union[str, Any]: super().__init__(UpperCAmelCase__ , task=UpperCAmelCase__ , patching_specs=UpperCAmelCase__ , use_past=UpperCAmelCase__ ) if not getattr(self._config , "pad_token_id" , UpperCAmelCase__ ): # TODO: how to do that better? __SCREAMING_SNAKE_CASE = 0 @property def UpperCAmelCase_ ( self : str ) -> Mapping[str, Mapping[int, str]]: __SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(UpperCAmelCase__ , direction="inputs" ) __SCREAMING_SNAKE_CASE = {0: "batch", 1: "past_sequence + sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return common_inputs @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: return self._config.n_layer @property def UpperCAmelCase_ ( self : List[Any] ) -> int: return self._config.n_head def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : PreTrainedTokenizer , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : int = -1 , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: __SCREAMING_SNAKE_CASE = super(UpperCAmelCase__ , self ).generate_dummy_inputs( UpperCAmelCase__ , batch_size=UpperCAmelCase__ , seq_length=UpperCAmelCase__ , is_pair=UpperCAmelCase__ , framework=UpperCAmelCase__ ) # We need to order the input in the way they appears in the forward() __SCREAMING_SNAKE_CASE = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = common_inputs["input_ids"].shape # Not using the same length for past_key_values __SCREAMING_SNAKE_CASE = seqlen + 2 __SCREAMING_SNAKE_CASE = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) __SCREAMING_SNAKE_CASE = [ (torch.zeros(UpperCAmelCase__ ), torch.zeros(UpperCAmelCase__ )) for _ in range(self.num_layers ) ] __SCREAMING_SNAKE_CASE = common_inputs["attention_mask"] if self.use_past: __SCREAMING_SNAKE_CASE = ordered_inputs["attention_mask"].dtype __SCREAMING_SNAKE_CASE = torch.cat( [ordered_inputs["attention_mask"], torch.ones(UpperCAmelCase__ , UpperCAmelCase__ , dtype=UpperCAmelCase__ )] , dim=1 ) return ordered_inputs @property def UpperCAmelCase_ ( self : Dict ) -> int: return 1_3
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" import os from typing import Optional import fsspec from fsspec.archive import AbstractArchiveFileSystem from fsspec.utils import DEFAULT_BLOCK_SIZE class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "" snake_case__ : str = ( None # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz ) snake_case__ : str = None # compression type in fsspec. ex: "gzip" snake_case__ : str = None # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz def __init__( self : Optional[int] , UpperCAmelCase__ : str = "" , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[dict] = None , **UpperCAmelCase__ : Optional[Any] ) -> Optional[Any]: super().__init__(self , **UpperCAmelCase__ ) # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode __SCREAMING_SNAKE_CASE = fsspec.open( UpperCAmelCase__ , mode="rb" , protocol=UpperCAmelCase__ , compression=self.compression , client_kwargs={ "requote_redirect_url": False, # see https://github.com/huggingface/datasets/pull/5459 "trust_env": True, # Enable reading proxy env variables. **(target_options or {}).pop("client_kwargs" , {} ), # To avoid issues if it was already passed. } , **(target_options or {}) , ) __SCREAMING_SNAKE_CASE = os.path.basename(self.file.path.split("::" )[0] ) __SCREAMING_SNAKE_CASE = ( self.compressed_name[: self.compressed_name.rindex("." )] if "." in self.compressed_name else self.compressed_name ) __SCREAMING_SNAKE_CASE = None @classmethod def UpperCAmelCase_ ( cls : List[str] , UpperCAmelCase__ : Any ) -> Union[str, Any]: # compressed file paths are always relative to the archive root return super()._strip_protocol(UpperCAmelCase__ ).lstrip("/" ) def UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: if self.dir_cache is None: __SCREAMING_SNAKE_CASE = {**self.file.fs.info(self.file.path ), "name": self.uncompressed_name} __SCREAMING_SNAKE_CASE = {f["name"]: f} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str ) -> Dict: return self.file.open().read() def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str , UpperCAmelCase__ : str = "rb" , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : Optional[int] , ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self._strip_protocol(UpperCAmelCase__ ) if mode != "rb": raise ValueError(F"""Tried to read with mode {mode} on file {self.file.path} opened with mode 'rb'""" ) return self.file.open() class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Dict = "bz2" snake_case__ : int = "bz2" snake_case__ : Dict = ".bz2" class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Union[str, Any] = "gzip" snake_case__ : Tuple = "gzip" snake_case__ : List[str] = ".gz" class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "lz4" snake_case__ : int = "lz4" snake_case__ : str = ".lz4" class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "xz" snake_case__ : List[Any] = "xz" snake_case__ : Any = ".xz" class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = "zstd" snake_case__ : Tuple = "zstd" snake_case__ : Union[str, Any] = ".zst" def __init__( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : str = "rb" , UpperCAmelCase__ : Optional[str] = None , UpperCAmelCase__ : Optional[dict] = None , UpperCAmelCase__ : int = DEFAULT_BLOCK_SIZE , **UpperCAmelCase__ : List[str] , ) -> Any: super().__init__( fo=UpperCAmelCase__ , mode=UpperCAmelCase__ , target_protocol=UpperCAmelCase__ , target_options=UpperCAmelCase__ , block_size=UpperCAmelCase__ , **UpperCAmelCase__ , ) # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2: # # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open # out.close = close # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only # # see https://github.com/intake/filesystem_spec/issues/725 __SCREAMING_SNAKE_CASE = self.file.__enter__ class UpperCamelCase_ : """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : str ) -> Dict: __SCREAMING_SNAKE_CASE = file_ def __enter__( self : int ) -> str: self._file.__enter__() return self def __exit__( self : int , *UpperCAmelCase__ : List[Any] , **UpperCAmelCase__ : int ) -> int: self._file.__exit__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def __iter__( self : int ) -> List[str]: return iter(self._file ) def UpperCAmelCase_ ( self : List[str] ) -> str: return next(self._file ) def __getattr__( self : int , UpperCAmelCase__ : int ) -> Union[str, Any]: return getattr(self._file , UpperCAmelCase__ ) def fixed_enter(*UpperCAmelCase__ : Optional[int] , **UpperCAmelCase__ : Any ): return WrappedFile(_enter(*UpperCAmelCase__ , **UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = fixed_enter
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) def UpperCAmelCase_ ( self : List[Any] ) -> str: self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["offset_mapping"] ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline a__ : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : List[Any] , **UpperCAmelCase__ : List[str] ) -> Dict: super().__init__(**UpperCAmelCase__ ) if self.framework != "pt": raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" ) # No specific FOR_XXX available yet def __call__( self : Optional[int] , UpperCAmelCase__ : Union[np.ndarray, bytes, str] , **UpperCAmelCase__ : List[str] ) -> List[Any]: return super().__call__(UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Any ) -> Any: __SCREAMING_SNAKE_CASE = {} if "candidate_labels" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["candidate_labels"] if "hypothesis_template" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["hypothesis_template"] return preprocess_params, {}, {} def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Union[str, Any]="This is a sound of {}." ) -> List[Any]: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): if audio.startswith("http://" ) or audio.startswith("https://" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __SCREAMING_SNAKE_CASE = requests.get(UpperCAmelCase__ ).content else: with open(UpperCAmelCase__ , "rb" ) as f: __SCREAMING_SNAKE_CASE = f.read() if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = ffmpeg_read(UpperCAmelCase__ , self.feature_extractor.sampling_rate ) if not isinstance(UpperCAmelCase__ , np.ndarray ): raise ValueError("We expect a numpy ndarray as input" ) if len(audio.shape ) != 1: raise ValueError("We expect a single channel audio input for ZeroShotAudioClassificationPipeline" ) __SCREAMING_SNAKE_CASE = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="pt" ) __SCREAMING_SNAKE_CASE = candidate_labels __SCREAMING_SNAKE_CASE = [hypothesis_template.format(UpperCAmelCase__ ) for x in candidate_labels] __SCREAMING_SNAKE_CASE = self.tokenizer(UpperCAmelCase__ , return_tensors=self.framework , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [text_inputs] return inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple ) -> str: __SCREAMING_SNAKE_CASE = model_inputs.pop("candidate_labels" ) __SCREAMING_SNAKE_CASE = model_inputs.pop("text_inputs" ) if isinstance(text_inputs[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = text_inputs[0] else: # Batching case. __SCREAMING_SNAKE_CASE = text_inputs[0][0] __SCREAMING_SNAKE_CASE = self.model(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "candidate_labels": candidate_labels, "logits": outputs.logits_per_audio, } return model_outputs def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = model_outputs.pop("candidate_labels" ) __SCREAMING_SNAKE_CASE = model_outputs["logits"][0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = logits.softmax(dim=0 ) __SCREAMING_SNAKE_CASE = probs.tolist() else: raise ValueError("`tf` framework not supported." ) __SCREAMING_SNAKE_CASE = [ {"score": score, "label": candidate_label} for score, candidate_label in sorted(zip(UpperCAmelCase__ , UpperCAmelCase__ ) , key=lambda UpperCAmelCase__ : -x[0] ) ] return result
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1