code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return price * (1 + tax_rate) if __name__ == "__main__": print(f'{price_plus_tax(1_00, 0.25) = }') print(f'{price_plus_tax(125.50, 0.05) = }')
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size 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 =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
_lowerCamelCase =2_56 # Modulus to hash a string _lowerCamelCase =1_00_00_03 def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) if p_len > t_len: return False SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =1 # Calculating the hash of pattern and substring of text for i in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =(ord(pattern[i] ) + p_hash * alphabet_size) % modulus SCREAMING_SNAKE_CASE =(ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue SCREAMING_SNAKE_CASE =(modulus_power * alphabet_size) % modulus for i in range(0, t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash SCREAMING_SNAKE_CASE =( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE ='abc1abc12' SCREAMING_SNAKE_CASE ='alskfjaldsabc1abc1abc12k23adsfabcabc' SCREAMING_SNAKE_CASE ='alskfjaldsk23adsfabcabc' assert rabin_karp(lowerCAmelCase_, lowerCAmelCase_ ) and not rabin_karp(lowerCAmelCase_, lowerCAmelCase_ ) # Test 2) SCREAMING_SNAKE_CASE ='ABABX' SCREAMING_SNAKE_CASE ='ABABZABABYABABX' assert rabin_karp(lowerCAmelCase_, lowerCAmelCase_ ) # Test 3) SCREAMING_SNAKE_CASE ='AAAB' SCREAMING_SNAKE_CASE ='ABAAAAAB' assert rabin_karp(lowerCAmelCase_, lowerCAmelCase_ ) # Test 4) SCREAMING_SNAKE_CASE ='abcdabcy' SCREAMING_SNAKE_CASE ='abcxabcdabxabcdabcdabcy' assert rabin_karp(lowerCAmelCase_, lowerCAmelCase_ ) # Test 5) SCREAMING_SNAKE_CASE ='Lü' SCREAMING_SNAKE_CASE ='Lüsai' assert rabin_karp(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ='Lue' assert not rabin_karp(lowerCAmelCase_, lowerCAmelCase_ ) print('Success.' ) if __name__ == "__main__": test_rabin_karp()
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "google/vit-base-patch16-224": "https://huggingface.co/vit-base-patch16-224/resolve/main/config.json", # See all ViT models at https://huggingface.co/models?filter=vit } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit' def __init__( self : int ,snake_case : Any=768 ,snake_case : List[Any]=12 ,snake_case : str=12 ,snake_case : Union[str, Any]=3072 ,snake_case : Optional[Any]="gelu" ,snake_case : str=0.0 ,snake_case : Tuple=0.0 ,snake_case : List[str]=0.02 ,snake_case : Optional[int]=1e-12 ,snake_case : Any=224 ,snake_case : List[Any]=16 ,snake_case : List[str]=3 ,snake_case : int=True ,snake_case : Union[str, Any]=16 ,**snake_case : Union[str, Any] ,): super().__init__(**snake_case ) 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 =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =encoder_stride class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = version.parse('1.11' ) @property def _lowerCAmelCase ( self : List[str] ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def _lowerCAmelCase ( self : Union[str, Any] ): return 1e-4
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'xmod' def __init__( self : Any ,snake_case : List[str]=30522 ,snake_case : int=768 ,snake_case : Dict=12 ,snake_case : Union[str, Any]=12 ,snake_case : Any=3072 ,snake_case : int="gelu" ,snake_case : Any=0.1 ,snake_case : Dict=0.1 ,snake_case : Any=512 ,snake_case : int=2 ,snake_case : Optional[int]=0.02 ,snake_case : Any=1e-12 ,snake_case : str=1 ,snake_case : List[str]=0 ,snake_case : Optional[Any]=2 ,snake_case : Any="absolute" ,snake_case : Union[str, Any]=True ,snake_case : str=None ,snake_case : Any=False ,snake_case : List[str]=2 ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=True ,snake_case : str=True ,snake_case : List[Any]=("en_XX",) ,snake_case : Optional[Any]=None ,**snake_case : List[str] ,): super().__init__(pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,**snake_case ) 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 SCREAMING_SNAKE_CASE =pre_norm SCREAMING_SNAKE_CASE =adapter_reduction_factor SCREAMING_SNAKE_CASE =adapter_layer_norm SCREAMING_SNAKE_CASE =adapter_reuse_layer_norm SCREAMING_SNAKE_CASE =ln_before_adapter SCREAMING_SNAKE_CASE =list(snake_case ) SCREAMING_SNAKE_CASE =default_language class a_ ( lowerCamelCase_ ): """simple docstring""" @property def _lowerCAmelCase ( self : List[Any] ): 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), ] )
334
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 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 =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_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.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , 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 a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : 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(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : 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(snake_case ) 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] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ), len(grid[0] ) if ( min(lowerCAmelCase_, lowerCAmelCase_ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) SCREAMING_SNAKE_CASE =0 count += depth_first_search(lowerCAmelCase_, row + 1, lowerCAmelCase_, lowerCAmelCase_ ) count += depth_first_search(lowerCAmelCase_, row - 1, lowerCAmelCase_, lowerCAmelCase_ ) count += depth_first_search(lowerCAmelCase_, lowerCAmelCase_, col + 1, lowerCAmelCase_ ) count += depth_first_search(lowerCAmelCase_, lowerCAmelCase_, col - 1, lowerCAmelCase_ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
_lowerCamelCase ="0.18.2" from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
334
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 # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( 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 _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( 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 snake_case__ ( ): """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()
334
1
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = (DPMSolverSinglestepScheduler,) __UpperCAmelCase = (('num_inference_steps', 25),) def _lowerCAmelCase ( self : List[Any] ,**snake_case : Any ): SCREAMING_SNAKE_CASE ={ 'num_train_timesteps': 1000, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, 'prediction_type': 'epsilon', 'thresholding': False, 'sample_max_value': 1.0, 'algorithm_type': 'dpmsolver++', 'solver_type': 'midpoint', 'lambda_min_clipped': -float('inf' ), 'variance_type': None, } config.update(**snake_case ) return config def _lowerCAmelCase ( self : List[Any] ,snake_case : Any=0 ,**snake_case : Dict ): SCREAMING_SNAKE_CASE =dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE =kwargs.pop('num_inference_steps' ,snake_case ) SCREAMING_SNAKE_CASE =self.dummy_sample SCREAMING_SNAKE_CASE =0.1 * sample SCREAMING_SNAKE_CASE =[residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE =self.get_scheduler_config(**snake_case ) SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) scheduler.set_timesteps(snake_case ) # copy over dummy past residuals SCREAMING_SNAKE_CASE =dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(snake_case ) SCREAMING_SNAKE_CASE =scheduler_class.from_pretrained(snake_case ) new_scheduler.set_timesteps(snake_case ) # copy over dummy past residuals SCREAMING_SNAKE_CASE =dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =sample, sample for t in range(snake_case ,time_step + scheduler.config.solver_order + 1 ): SCREAMING_SNAKE_CASE =scheduler.step(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample SCREAMING_SNAKE_CASE =new_scheduler.step(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _lowerCAmelCase ( self : Any ): pass def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Union[str, Any]=0 ,**snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE =kwargs.pop('num_inference_steps' ,snake_case ) SCREAMING_SNAKE_CASE =self.dummy_sample SCREAMING_SNAKE_CASE =0.1 * sample SCREAMING_SNAKE_CASE =[residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE =self.get_scheduler_config() SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) scheduler.set_timesteps(snake_case ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE =dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(snake_case ) SCREAMING_SNAKE_CASE =scheduler_class.from_pretrained(snake_case ) # copy over dummy past residuals new_scheduler.set_timesteps(snake_case ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE =dummy_past_residuals[: new_scheduler.config.solver_order] SCREAMING_SNAKE_CASE =scheduler.step(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample SCREAMING_SNAKE_CASE =new_scheduler.step(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _lowerCAmelCase ( self : List[str] ,snake_case : Optional[Any]=None ,**snake_case : Union[str, Any] ): if scheduler is None: SCREAMING_SNAKE_CASE =self.scheduler_classes[0] SCREAMING_SNAKE_CASE =self.get_scheduler_config(**snake_case ) SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) SCREAMING_SNAKE_CASE =self.scheduler_classes[0] SCREAMING_SNAKE_CASE =self.get_scheduler_config(**snake_case ) SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) SCREAMING_SNAKE_CASE =10 SCREAMING_SNAKE_CASE =self.dummy_model() SCREAMING_SNAKE_CASE =self.dummy_sample_deter scheduler.set_timesteps(snake_case ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =scheduler.step(snake_case ,snake_case ,snake_case ).prev_sample return sample def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE =50 SCREAMING_SNAKE_CASE =self.dummy_model() SCREAMING_SNAKE_CASE =self.dummy_sample_deter scheduler.set_timesteps(snake_case ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =scheduler.step(snake_case ,snake_case ,snake_case ).prev_sample SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.2_574 ) < 1e-3 def _lowerCAmelCase ( self : int ): for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=snake_case ) def _lowerCAmelCase ( self : List[Any] ): # make sure that iterating over schedulers with same config names gives same results # for defaults SCREAMING_SNAKE_CASE =DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) SCREAMING_SNAKE_CASE =self.full_loop(scheduler=snake_case ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.2_791 ) < 1e-3 SCREAMING_SNAKE_CASE =DEISMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE =DPMSolverMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE =UniPCMultistepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE =DPMSolverSinglestepScheduler.from_config(scheduler.config ) SCREAMING_SNAKE_CASE =self.full_loop(scheduler=snake_case ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.2_791 ) < 1e-3 def _lowerCAmelCase ( self : Optional[Any] ): self.check_over_configs(thresholding=snake_case ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=snake_case ,prediction_type=snake_case ,sample_max_value=snake_case ,algorithm_type='dpmsolver++' ,solver_order=snake_case ,solver_type=snake_case ,) def _lowerCAmelCase ( self : Optional[int] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=snake_case ) def _lowerCAmelCase ( self : List[str] ): for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=snake_case ,solver_type=snake_case ,prediction_type=snake_case ,algorithm_type=snake_case ,) SCREAMING_SNAKE_CASE =self.full_loop( solver_order=snake_case ,solver_type=snake_case ,prediction_type=snake_case ,algorithm_type=snake_case ,) assert not torch.isnan(snake_case ).any(), "Samples have nan numbers" def _lowerCAmelCase ( self : Optional[Any] ): self.check_over_configs(lower_order_final=snake_case ) self.check_over_configs(lower_order_final=snake_case ) def _lowerCAmelCase ( self : Tuple ): self.check_over_configs(lambda_min_clipped=-float('inf' ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def _lowerCAmelCase ( self : Tuple ): self.check_over_configs(variance_type=snake_case ) self.check_over_configs(variance_type='learned_range' ) def _lowerCAmelCase ( self : List[str] ): for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=snake_case ,time_step=0 ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.full_loop() SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.2_791 ) < 1e-3 def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.full_loop(use_karras_sigmas=snake_case ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.2_248 ) < 1e-3 def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.full_loop(prediction_type='v_prediction' ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.1_453 ) < 1e-3 def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.full_loop(prediction_type='v_prediction' ,use_karras_sigmas=snake_case ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_mean.item() - 0.0_649 ) < 1e-3 def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.scheduler_classes[0] SCREAMING_SNAKE_CASE =self.get_scheduler_config(thresholding=snake_case ,dynamic_thresholding_ratio=0 ) SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) SCREAMING_SNAKE_CASE =10 SCREAMING_SNAKE_CASE =self.dummy_model() SCREAMING_SNAKE_CASE =self.dummy_sample_deter.half() scheduler.set_timesteps(snake_case ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =scheduler.step(snake_case ,snake_case ,snake_case ).prev_sample assert sample.dtype == torch.floataa
334
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return sum(i for i in range(1, number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") _lowerCamelCase =int(input("Enter number: ").strip()) print(f'{number} is {"" if perfect(number) else "not "}a Perfect Number.')
334
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
1
import requests from bsa import BeautifulSoup def snake_case__ ( lowerCAmelCase_ = "AAPL" ): """simple docstring""" SCREAMING_SNAKE_CASE =F'https://in.finance.yahoo.com/quote/{symbol}?s={symbol}' SCREAMING_SNAKE_CASE =BeautifulSoup(requests.get(lowerCAmelCase_ ).text, 'html.parser' ) SCREAMING_SNAKE_CASE ='My(6px) Pos(r) smartphone_Mt(6px)' return soup.find('div', class_=class_ ).find('span' ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f'Current {symbol:<4} stock price is {stock_price(symbol):>8}')
334
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size 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 SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": 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(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) 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 =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/s2t-small-librispeech-asr": ( "https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'speech_to_text' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : Dict ,snake_case : Union[str, Any]=10000 ,snake_case : Any=12 ,snake_case : Optional[int]=2048 ,snake_case : Optional[int]=4 ,snake_case : List[str]=6 ,snake_case : int=2048 ,snake_case : List[str]=4 ,snake_case : Any=0.0 ,snake_case : List[Any]=0.0 ,snake_case : str=True ,snake_case : Optional[Any]=True ,snake_case : str="relu" ,snake_case : str=256 ,snake_case : Union[str, Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : List[str]=0.0 ,snake_case : str=0.02 ,snake_case : Any=2 ,snake_case : Any=True ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Optional[int]=2 ,snake_case : Optional[Any]=6000 ,snake_case : Union[str, Any]=1024 ,snake_case : Tuple=2 ,snake_case : Optional[int]=(5, 5) ,snake_case : Any=1024 ,snake_case : Union[str, Any]=80 ,snake_case : Optional[Any]=1 ,**snake_case : Tuple ,): SCREAMING_SNAKE_CASE =vocab_size 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 =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =max_source_positions SCREAMING_SNAKE_CASE =max_target_positions SCREAMING_SNAKE_CASE =num_conv_layers SCREAMING_SNAKE_CASE =list(snake_case ) SCREAMING_SNAKE_CASE =conv_channels SCREAMING_SNAKE_CASE =input_feat_per_channel SCREAMING_SNAKE_CASE =input_channels if len(self.conv_kernel_sizes ) != self.num_conv_layers: raise ValueError( 'Configuration for convolutional module is incorrect. ' 'It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` ' f'but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes )}`, ' f'`config.num_conv_layers = {self.num_conv_layers}`.' ) super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=10 ): """simple docstring""" SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=10 ): """simple docstring""" SCREAMING_SNAKE_CASE =[] for step in range(lowerCAmelCase_ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'schedule.bin' ) torch.save(scheduler.state_dict(), lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_ ) scheduler.load_state_dict(lowerCAmelCase_ ) return lrs @require_torch class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : List[str] ,snake_case : Dict ,snake_case : Optional[int] ): self.assertEqual(len(snake_case ) ,len(snake_case ) ) for a, b in zip(snake_case ,snake_case ): self.assertAlmostEqual(snake_case ,snake_case ,delta=snake_case ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =torch.tensor([0.1, -0.2, -0.1] ,requires_grad=snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([0.4, 0.2, -0.5] ) SCREAMING_SNAKE_CASE =nn.MSELoss() # No warmup, constant schedule, no gradient clipping SCREAMING_SNAKE_CASE =AdamW(params=[w] ,lr=2e-1 ,weight_decay=0.0 ) for _ in range(100 ): SCREAMING_SNAKE_CASE =criterion(snake_case ,snake_case ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() ,[0.4, 0.2, -0.5] ,tol=1e-2 ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =torch.tensor([0.1, -0.2, -0.1] ,requires_grad=snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([0.4, 0.2, -0.5] ) SCREAMING_SNAKE_CASE =nn.MSELoss() # No warmup, constant schedule, no gradient clipping SCREAMING_SNAKE_CASE =Adafactor( params=[w] ,lr=1e-2 ,eps=(1e-30, 1e-3) ,clip_threshold=1.0 ,decay_rate=-0.8 ,betaa=snake_case ,weight_decay=0.0 ,relative_step=snake_case ,scale_parameter=snake_case ,warmup_init=snake_case ,) for _ in range(1000 ): SCREAMING_SNAKE_CASE =criterion(snake_case ,snake_case ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() ,[0.4, 0.2, -0.5] ,tol=1e-2 ) @require_torch class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = nn.Linear(50 , 50 ) if is_torch_available() else None __UpperCAmelCase = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None __UpperCAmelCase = 10 def _lowerCAmelCase ( self : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : str ,snake_case : Tuple=None ): self.assertEqual(len(snake_case ) ,len(snake_case ) ) for a, b in zip(snake_case ,snake_case ): self.assertAlmostEqual(snake_case ,snake_case ,delta=snake_case ,msg=snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE ={'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) SCREAMING_SNAKE_CASE ={ get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =data SCREAMING_SNAKE_CASE =scheduler_func(self.optimizer ,**snake_case ) self.assertEqual(len([scheduler.get_lr()[0]] ) ,1 ) SCREAMING_SNAKE_CASE =unwrap_schedule(snake_case ,self.num_steps ) self.assertListAlmostEqual( snake_case ,snake_case ,tol=1e-2 ,msg=f'failed for {scheduler_func} in normal scheduler' ,) SCREAMING_SNAKE_CASE =scheduler_func(self.optimizer ,**snake_case ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(snake_case ) # wrap to test picklability of the schedule SCREAMING_SNAKE_CASE =unwrap_and_save_reload_schedule(snake_case ,self.num_steps ) self.assertListEqual(snake_case ,snake_case ,msg=f'failed for {scheduler_func} in save and reload' ) class a_ : """simple docstring""" def __init__( self : List[str] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =fn def __call__( self : Optional[int] ,*snake_case : List[str] ,**snake_case : Any ): return self.fn(*snake_case ,**snake_case ) @classmethod def _lowerCAmelCase ( self : Any ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =list(map(self ,scheduler.lr_lambdas ) )
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) 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 =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
1
import itertools import string from collections.abc import Generator, Iterable def snake_case__ ( 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 snake_case__ ( 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 snake_case__ ( 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 snake_case__ ( 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 snake_case__ ( 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
334
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
1
import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class a_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = DebertaTokenizer __UpperCAmelCase = True __UpperCAmelCase = DebertaTokenizerFast def _lowerCAmelCase ( self : Dict ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE =[ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '[UNK]', ] SCREAMING_SNAKE_CASE =dict(zip(snake_case ,range(len(snake_case ) ) ) ) SCREAMING_SNAKE_CASE =['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] SCREAMING_SNAKE_CASE ={'unk_token': '[UNK]'} SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as fp: fp.write(json.dumps(snake_case ) + '\n' ) with open(self.merges_file ,'w' ,encoding='utf-8' ) as fp: fp.write('\n'.join(snake_case ) ) def _lowerCAmelCase ( self : Dict ,**snake_case : str ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname ,**snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ): SCREAMING_SNAKE_CASE ='lower newer' SCREAMING_SNAKE_CASE ='lower newer' return input_text, output_text def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.get_tokenizer() SCREAMING_SNAKE_CASE ='lower newer' SCREAMING_SNAKE_CASE =['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er'] SCREAMING_SNAKE_CASE =tokenizer.tokenize(snake_case ) self.assertListEqual(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE =[0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case ) ,snake_case ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.get_tokenizer() SCREAMING_SNAKE_CASE =tokenizer('Hello' ,'World' ) SCREAMING_SNAKE_CASE =[0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['token_type_ids'] ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.tokenizer_class.from_pretrained('microsoft/deberta-base' ) SCREAMING_SNAKE_CASE =tokenizer.encode('sequence builders' ,add_special_tokens=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.encode('multi-sequence build' ,add_special_tokens=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.encode( 'sequence builders' ,add_special_tokens=snake_case ,add_prefix_space=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.encode( 'sequence builders' ,'multi-sequence build' ,add_special_tokens=snake_case ,add_prefix_space=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.build_inputs_with_special_tokens(snake_case ) SCREAMING_SNAKE_CASE =tokenizer.build_inputs_with_special_tokens(snake_case ,snake_case ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =[self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: SCREAMING_SNAKE_CASE =tokenizer_class.from_pretrained('microsoft/deberta-base' ) SCREAMING_SNAKE_CASE =[ 'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations', 'ALBERT incorporates two parameter reduction techniques', 'The first one is a factorized embedding parameterization. By decomposing the large vocabulary' ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of' ' vocabulary embedding.', ] SCREAMING_SNAKE_CASE =tokenizer(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =[tokenizer.decode(snake_case ,skip_special_tokens=snake_case ) for seq in encoding['input_ids']] # fmt: off SCREAMING_SNAKE_CASE ={ 'input_ids': [ [1, 2118, 11126, 565, 35, 83, 25191, 163, 18854, 13, 12156, 12, 16101, 25376, 13807, 9, 22205, 27893, 1635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2118, 11126, 565, 24536, 80, 43797, 4878, 7373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 133, 78, 65, 16, 10, 3724, 1538, 33183, 11303, 43797, 1938, 4, 870, 24165, 29105, 5, 739, 32644, 33183, 11303, 36173, 88, 80, 650, 7821, 45940, 6, 52, 2559, 5, 1836, 9, 5, 7397, 13171, 31, 5, 1836, 9, 32644, 33183, 11303, 4, 2] ], 'token_type_ids': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], 'attention_mask': [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on SCREAMING_SNAKE_CASE =[ 'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations', 'ALBERT incorporates two parameter reduction techniques', 'The first one is a factorized embedding parameterization. By decomposing the large vocabulary' ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of' ' vocabulary embedding.', ] self.assertDictEqual(encoding.data ,snake_case ) for expected, decoded in zip(snake_case ,snake_case ): self.assertEqual(snake_case ,snake_case )
334
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: writer.write({'col_1': 'foo', 'col_2': 1}, key=1 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=2 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =value @pytest.mark.parametrize('optimized_int_type, expected_dtype', [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype', [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ], ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
1
import re def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if len(re.findall('[ATCG]', lowerCAmelCase_ ) ) != len(lowerCAmelCase_ ): raise ValueError('Invalid Strand' ) return dna.translate(dna.maketrans('ATCG', 'TAGC' ) ) if __name__ == "__main__": import doctest doctest.testmod()
334
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
1
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ={ 'en': 'Machine learning is great, isn\'t it?', 'ru': 'Машинное обучение - это здорово, не так ли?', 'de': 'Maschinelles Lernen ist großartig, oder?', } # BLUE scores as follows: # "pair": [fairseq, transformers] SCREAMING_SNAKE_CASE ={ 'ru-en': ['[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)', '39.20'], 'en-ru': ['[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)', '33.47'], 'en-de': ['[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)', '42.83'], 'de-en': ['[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)', '41.35'], } SCREAMING_SNAKE_CASE =F'{src_lang}-{tgt_lang}' SCREAMING_SNAKE_CASE =F'\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR\'s WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "facebook/wmt19-{src_lang}-{tgt_lang}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn\'t seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn\'t support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR\'s WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n' os.makedirs(lowerCAmelCase_, exist_ok=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'README.md' ) print(F'Generating {path}' ) with open(lowerCAmelCase_, 'w', encoding='utf-8' ) as f: f.write(lowerCAmelCase_ ) # make sure we are under the root of the project _lowerCamelCase =Path(__file__).resolve().parent.parent.parent _lowerCamelCase =repo_dir / "model_cards" for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =model_name.split("-") _lowerCamelCase =model_cards_dir / "facebook" / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
334
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
1
import argparse from pathlib import Path import requests import torch from PIL import Image from transformers import ( RobertaTokenizer, TrOCRConfig, TrOCRForCausalLM, TrOCRProcessor, VisionEncoderDecoderModel, ViTConfig, ViTImageProcessor, ViTModel, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[] for i in range(encoder_config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( (F'encoder.deit.blocks.{i}.norm1.weight', F'encoder.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'encoder.deit.blocks.{i}.norm1.bias', F'encoder.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (F'encoder.deit.blocks.{i}.attn.proj.weight', F'encoder.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (F'encoder.deit.blocks.{i}.attn.proj.bias', F'encoder.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append( (F'encoder.deit.blocks.{i}.norm2.weight', F'encoder.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'encoder.deit.blocks.{i}.norm2.bias', F'encoder.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append( (F'encoder.deit.blocks.{i}.mlp.fc1.weight', F'encoder.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append( (F'encoder.deit.blocks.{i}.mlp.fc1.bias', F'encoder.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append( (F'encoder.deit.blocks.{i}.mlp.fc2.weight', F'encoder.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'encoder.deit.blocks.{i}.mlp.fc2.bias', F'encoder.encoder.layer.{i}.output.dense.bias') ) # cls token, position embeddings and patch embeddings of encoder rename_keys.extend( [ ('encoder.deit.cls_token', 'encoder.embeddings.cls_token'), ('encoder.deit.pos_embed', 'encoder.embeddings.position_embeddings'), ('encoder.deit.patch_embed.proj.weight', 'encoder.embeddings.patch_embeddings.projection.weight'), ('encoder.deit.patch_embed.proj.bias', 'encoder.embeddings.patch_embeddings.projection.bias'), ('encoder.deit.norm.weight', 'encoder.layernorm.weight'), ('encoder.deit.norm.bias', 'encoder.layernorm.bias'), ] ) return rename_keys def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for i in range(encoder_config.num_hidden_layers ): # queries, keys and values (only weights, no biases) SCREAMING_SNAKE_CASE =state_dict.pop(F'encoder.deit.blocks.{i}.attn.qkv.weight' ) SCREAMING_SNAKE_CASE =in_proj_weight[ : encoder_config.hidden_size, : ] SCREAMING_SNAKE_CASE =in_proj_weight[ encoder_config.hidden_size : encoder_config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE =in_proj_weight[ -encoder_config.hidden_size :, : ] def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =dct.pop(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =val def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if "handwritten" in checkpoint_url: SCREAMING_SNAKE_CASE ='https://fki.tic.heia-fr.ch/static/img/a01-122-02-00.jpg' # industry # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-12.jpg" # have # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02-10.jpg" # let # url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg" # # url = "https://fki.tic.heia-fr.ch/static/img/a01-122.jpg" elif "printed" in checkpoint_url or "stage1" in checkpoint_url: SCREAMING_SNAKE_CASE ='https://www.researchgate.net/profile/Dinh-Sang/publication/338099565/figure/fig8/AS:840413229350922@1577381536857/An-receipt-example-in-the-SROIE-2019-dataset_Q640.jpg' SCREAMING_SNAKE_CASE =Image.open(requests.get(lowerCAmelCase_, stream=lowerCAmelCase_ ).raw ).convert('RGB' ) return im @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =ViTConfig(image_size=384, qkv_bias=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =TrOCRConfig() # size of the architecture if "base" in checkpoint_url: SCREAMING_SNAKE_CASE =768 elif "large" in checkpoint_url: # use ViT-large encoder SCREAMING_SNAKE_CASE =1024 SCREAMING_SNAKE_CASE =4096 SCREAMING_SNAKE_CASE =24 SCREAMING_SNAKE_CASE =16 SCREAMING_SNAKE_CASE =1024 else: raise ValueError('Should either find \'base\' or \'large\' in checkpoint URL' ) # the large-printed + stage1 checkpoints uses sinusoidal position embeddings, no layernorm afterwards if "large-printed" in checkpoint_url or "stage1" in checkpoint_url: SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE ='relu' SCREAMING_SNAKE_CASE =1024 SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =False # load HuggingFace model SCREAMING_SNAKE_CASE =ViTModel(lowerCAmelCase_, add_pooling_layer=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =TrOCRForCausalLM(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =VisionEncoderDecoderModel(encoder=lowerCAmelCase_, decoder=lowerCAmelCase_ ) model.eval() # load state_dict of original model, rename some keys SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, map_location='cpu', check_hash=lowerCAmelCase_ )['model'] SCREAMING_SNAKE_CASE =create_rename_keys(lowerCAmelCase_, lowerCAmelCase_ ) for src, dest in rename_keys: rename_key(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) read_in_q_k_v(lowerCAmelCase_, lowerCAmelCase_ ) # remove parameters we don't need del state_dict["encoder.deit.head.weight"] del state_dict["encoder.deit.head.bias"] del state_dict["decoder.version"] # add prefix to decoder keys for key, val in state_dict.copy().items(): SCREAMING_SNAKE_CASE =state_dict.pop(lowerCAmelCase_ ) if key.startswith('decoder' ) and "output_projection" not in key: SCREAMING_SNAKE_CASE =val else: SCREAMING_SNAKE_CASE =val # load state dict model.load_state_dict(lowerCAmelCase_ ) # Check outputs on an image SCREAMING_SNAKE_CASE =ViTImageProcessor(size=encoder_config.image_size ) SCREAMING_SNAKE_CASE =RobertaTokenizer.from_pretrained('roberta-large' ) SCREAMING_SNAKE_CASE =TrOCRProcessor(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =processor(images=prepare_img(lowerCAmelCase_ ), return_tensors='pt' ).pixel_values # verify logits SCREAMING_SNAKE_CASE =torch.tensor([[model.config.decoder.decoder_start_token_id]] ) SCREAMING_SNAKE_CASE =model(pixel_values=lowerCAmelCase_, decoder_input_ids=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =outputs.logits SCREAMING_SNAKE_CASE =torch.Size([1, 1, 50265] ) if "trocr-base-handwritten" in checkpoint_url: SCREAMING_SNAKE_CASE =torch.tensor( [-1.4502, -4.6683, -0.5347, -2.9291, 9.1435, -3.0571, 8.9764, 1.7560, 8.7358, -1.5311] ) elif "trocr-large-handwritten" in checkpoint_url: SCREAMING_SNAKE_CASE =torch.tensor( [-2.6437, -1.3129, -2.2596, -5.3455, 6.3539, 1.7604, 5.4991, 1.4702, 5.6113, 2.0170] ) elif "trocr-base-printed" in checkpoint_url: SCREAMING_SNAKE_CASE =torch.tensor( [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210] ) elif "trocr-large-printed" in checkpoint_url: SCREAMING_SNAKE_CASE =torch.tensor( [-6.0162, -7.0959, 4.4155, -5.1063, 7.0468, -3.1631, 2.6466, -0.3081, -0.8106, -1.7535] ) if "stage1" not in checkpoint_url: assert logits.shape == expected_shape, "Shape of logits not as expected" assert torch.allclose(logits[0, 0, :10], lowerCAmelCase_, atol=1e-3 ), "First elements of logits not as expected" Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase_ ) print(F'Saving processor to {pytorch_dump_folder_path}' ) processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() parser.add_argument( "--checkpoint_url", default="https://layoutlm.blob.core.windows.net/trocr/model_zoo/fairseq/trocr-base-handwritten.pt", type=str, help="URL to the original PyTorch checkpoint (.pth file).", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) _lowerCamelCase =parser.parse_args() convert_tr_ocr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from ...utils.dataclasses import ( ComputeEnvironment, DistributedType, DynamoBackend, PrecisionType, SageMakerDistributedType, ) from ..menu import BulletMenu _lowerCamelCase =[ "EAGER", "AOT_EAGER", "INDUCTOR", "NVFUSER", "AOT_NVFUSER", "AOT_CUDAGRAPHS", "OFI", "FX2TRT", "ONNXRT", "IPEX", ] def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=None, lowerCAmelCase_=None, lowerCAmelCase_=None ): """simple docstring""" SCREAMING_SNAKE_CASE =True while ask_again: SCREAMING_SNAKE_CASE =input(lowerCAmelCase_ ) try: if default is not None and len(lowerCAmelCase_ ) == 0: return default return convert_value(lowerCAmelCase_ ) if convert_value is not None else result except Exception: if error_message is not None: print(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=[], lowerCAmelCase_=None, lowerCAmelCase_=0 ): """simple docstring""" SCREAMING_SNAKE_CASE =BulletMenu(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =menu.run(default_choice=lowerCAmelCase_ ) return convert_value(lowerCAmelCase_ ) if convert_value is not None else result def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =int(lowerCAmelCase_ ) return ComputeEnvironment(['LOCAL_MACHINE', 'AMAZON_SAGEMAKER'][value] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =int(lowerCAmelCase_ ) return DistributedType(['NO', 'MULTI_CPU', 'MULTI_XPU', 'MULTI_GPU', 'MULTI_NPU', 'TPU'][value] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =int(lowerCAmelCase_ ) return DynamoBackend(DYNAMO_BACKENDS[value] ).value def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =int(lowerCAmelCase_ ) return PrecisionType(['no', 'fp16', 'bf16', 'fp8'][value] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =int(lowerCAmelCase_ ) return SageMakerDistributedType(['NO', 'DATA_PARALLEL', 'MODEL_PARALLEL'][value] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return {"yes": True, "no": False}[value.lower()] class a_ ( argparse.RawDescriptionHelpFormatter ): """simple docstring""" def _lowerCAmelCase ( self : List[str] ,snake_case : str ,snake_case : Optional[int] ,snake_case : Optional[Any] ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =super()._format_usage(snake_case ,snake_case ,snake_case ,snake_case ) SCREAMING_SNAKE_CASE =usage.replace('<command> [<args>] ' ,'' ) return usage
334
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
1
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness _lowerCamelCase ="\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n" _lowerCamelCase ="\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper \"Evaluating Large Language Models Trained on Code\"\n(https://arxiv.org/abs/2107.03374).\n" _lowerCamelCase ="\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric(\"code_eval\")\n >>> test_cases = [\"assert add(2,3)==5\"]\n >>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {'pass@1': 0.5, 'pass@2': 1.0}\n" _lowerCamelCase ="\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe \"code_eval\" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper \"Evaluating Large\nLanguage Models Trained on Code\" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\"\n\n################################################################################\\n" _lowerCamelCase ="The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE." @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' ) ), 'references': datasets.Value('string' ), } ) ,homepage='https://github.com/openai/human-eval' ,codebase_urls=['https://github.com/openai/human-eval'] ,reference_urls=['https://github.com/openai/human-eval'] ,license=_LICENSE ,) def _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Optional[int]=[1, 10, 100] ,snake_case : Union[str, Any]=4 ,snake_case : Tuple=3.0 ): if os.getenv('HF_ALLOW_CODE_EVAL' ,0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError('This metric is currently not supported on Windows.' ) with ThreadPoolExecutor(max_workers=snake_case ) as executor: SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =Counter() SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =defaultdict(snake_case ) for task_id, (candidates, test_case) in enumerate(zip(snake_case ,snake_case ) ): for candidate in candidates: SCREAMING_SNAKE_CASE =candidate + '\n' + test_case SCREAMING_SNAKE_CASE =(test_program, timeout, task_id, completion_id[task_id]) SCREAMING_SNAKE_CASE =executor.submit(snake_case ,*snake_case ) futures.append(snake_case ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(snake_case ): SCREAMING_SNAKE_CASE =future.result() results[result["task_id"]].append((result['completion_id'], result) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =[], [] for result in results.values(): result.sort() SCREAMING_SNAKE_CASE =[r[1]['passed'] for r in result] total.append(len(snake_case ) ) correct.append(sum(snake_case ) ) SCREAMING_SNAKE_CASE =np.array(snake_case ) SCREAMING_SNAKE_CASE =np.array(snake_case ) SCREAMING_SNAKE_CASE =k SCREAMING_SNAKE_CASE ={f'pass@{k}': estimate_pass_at_k(snake_case ,snake_case ,snake_case ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" def estimator(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1 ) ) if isinstance(lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =itertools.repeat(lowerCAmelCase_, len(lowerCAmelCase_ ) ) else: assert len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =iter(lowerCAmelCase_ ) return np.array([estimator(int(lowerCAmelCase_ ), int(lowerCAmelCase_ ), lowerCAmelCase_ ) for n, c in zip(lowerCAmelCase_, lowerCAmelCase_ )] )
334
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): 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 =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): 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 _lowerCAmelCase ( self : Optional[int] ): return SqueezeBertConfig( embedding_size=self.hidden_size ,vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,attention_probs_dropout_prob=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,q_groups=self.q_groups ,k_groups=self.k_groups ,v_groups=self.v_groups ,post_attention_groups=self.post_attention_groups ,intermediate_groups=self.intermediate_groups ,output_groups=self.output_groups ,) def _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=snake_case ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) 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( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, 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)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto.configuration_auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'upernet' def __init__( self : int ,snake_case : Tuple=None ,snake_case : List[str]=512 ,snake_case : str=0.02 ,snake_case : Tuple=[1, 2, 3, 6] ,snake_case : List[Any]=True ,snake_case : Any=0.4 ,snake_case : Optional[int]=384 ,snake_case : Tuple=256 ,snake_case : Dict=1 ,snake_case : Any=False ,snake_case : str=255 ,**snake_case : str ,): super().__init__(**snake_case ) 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=['stage1', 'stage2', 'stage3', 'stage4'] ) elif isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =backbone_config.get('model_type' ) SCREAMING_SNAKE_CASE =CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE =config_class.from_dict(snake_case ) SCREAMING_SNAKE_CASE =backbone_config SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =pool_scales SCREAMING_SNAKE_CASE =use_auxiliary_head SCREAMING_SNAKE_CASE =auxiliary_loss_weight SCREAMING_SNAKE_CASE =auxiliary_in_channels SCREAMING_SNAKE_CASE =auxiliary_channels SCREAMING_SNAKE_CASE =auxiliary_num_convs SCREAMING_SNAKE_CASE =auxiliary_concat_input SCREAMING_SNAKE_CASE =loss_ignore_index def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.backbone_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging _lowerCamelCase =logging.get_logger(__name__) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = ['pixel_values'] def __init__( self : Dict ,snake_case : bool = True ,snake_case : Dict[str, int] = None ,snake_case : PILImageResampling = PILImageResampling.BICUBIC ,snake_case : bool = True ,snake_case : Dict[str, int] = None ,snake_case : bool = True ,snake_case : Union[int, float] = 1 / 255 ,snake_case : bool = True ,snake_case : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN ,snake_case : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =size if size is not None else {'shortest_edge': 224} SCREAMING_SNAKE_CASE =get_size_dict(snake_case ,default_to_square=snake_case ) SCREAMING_SNAKE_CASE =crop_size if crop_size is not None else {'height': 224, 'width': 224} SCREAMING_SNAKE_CASE =get_size_dict(snake_case ,param_name='crop_size' ) SCREAMING_SNAKE_CASE =do_resize SCREAMING_SNAKE_CASE =size SCREAMING_SNAKE_CASE =resample SCREAMING_SNAKE_CASE =do_center_crop SCREAMING_SNAKE_CASE =crop_size SCREAMING_SNAKE_CASE =do_rescale SCREAMING_SNAKE_CASE =rescale_factor SCREAMING_SNAKE_CASE =do_normalize SCREAMING_SNAKE_CASE =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN SCREAMING_SNAKE_CASE =image_std if image_std is not None else IMAGENET_DEFAULT_STD def _lowerCAmelCase ( self : List[str] ,snake_case : np.ndarray ,snake_case : Dict[str, int] ,snake_case : PILImageResampling = PILImageResampling.BICUBIC ,snake_case : Optional[Union[str, ChannelDimension]] = None ,**snake_case : Tuple ,): SCREAMING_SNAKE_CASE =get_size_dict(snake_case ,default_to_square=snake_case ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: SCREAMING_SNAKE_CASE =int((256 / 224) * size['shortest_edge'] ) SCREAMING_SNAKE_CASE =get_resize_output_image_size(snake_case ,size=snake_case ,default_to_square=snake_case ) SCREAMING_SNAKE_CASE ={'height': output_size[0], 'width': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}' ) return resize( snake_case ,size=(size_dict['height'], size_dict['width']) ,resample=snake_case ,data_format=snake_case ,**snake_case ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : np.ndarray ,snake_case : Dict[str, int] ,snake_case : Optional[Union[str, ChannelDimension]] = None ,**snake_case : str ,): SCREAMING_SNAKE_CASE =get_size_dict(snake_case ) if "height" not in size or "width" not in size: raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}' ) return center_crop(snake_case ,size=(size['height'], size['width']) ,data_format=snake_case ,**snake_case ) def _lowerCAmelCase ( self : List[Any] ,snake_case : np.ndarray ,snake_case : Union[int, float] ,snake_case : Optional[Union[str, ChannelDimension]] = None ,**snake_case : Tuple ,): return rescale(snake_case ,scale=snake_case ,data_format=snake_case ,**snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : np.ndarray ,snake_case : Union[float, List[float]] ,snake_case : Union[float, List[float]] ,snake_case : Optional[Union[str, ChannelDimension]] = None ,**snake_case : Tuple ,): return normalize(snake_case ,mean=snake_case ,std=snake_case ,data_format=snake_case ,**snake_case ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : ImageInput ,snake_case : Optional[bool] = None ,snake_case : Optional[Dict[str, int]] = None ,snake_case : PILImageResampling = None ,snake_case : Optional[bool] = None ,snake_case : Optional[Dict[str, int]] = None ,snake_case : Optional[bool] = None ,snake_case : Optional[float] = None ,snake_case : Optional[bool] = None ,snake_case : Optional[Union[float, Iterable[float]]] = None ,snake_case : Optional[Union[float, Iterable[float]]] = None ,snake_case : Optional[TensorType] = None ,snake_case : ChannelDimension = ChannelDimension.FIRST ,**snake_case : Optional[int] ,): SCREAMING_SNAKE_CASE =do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE =resample if resample is not None else self.resample SCREAMING_SNAKE_CASE =do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE =do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE =rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE =do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE =image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE =image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE =size if size is not None else self.size SCREAMING_SNAKE_CASE =get_size_dict(snake_case ,default_to_square=snake_case ) SCREAMING_SNAKE_CASE =crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE =get_size_dict(snake_case ,param_name='crop_size' ) SCREAMING_SNAKE_CASE =make_list_of_images(snake_case ) if not valid_images(snake_case ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE =[to_numpy_array(snake_case ) for image in images] if do_resize: SCREAMING_SNAKE_CASE =[self.resize(snake_case ,snake_case ,snake_case ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE =[self.center_crop(snake_case ,snake_case ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE =[self.rescale(snake_case ,snake_case ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE =[self.normalize(snake_case ,snake_case ,snake_case ) for image in images] SCREAMING_SNAKE_CASE =[to_channel_dimension_format(snake_case ,snake_case ) for image in images] SCREAMING_SNAKE_CASE ={'pixel_values': images} return BatchFeature(data=snake_case ,tensor_type=snake_case )
334
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =0 # if input_string is "aba" than new_input_string become "a|b|a" SCREAMING_SNAKE_CASE ='' SCREAMING_SNAKE_CASE ='' # append each character + "|" in new_string for range(0, length-1) for i in input_string[: len(lowerCAmelCase_ ) - 1]: new_input_string += i + "|" # append last character new_input_string += input_string[-1] # we will store the starting and ending of previous furthest ending palindromic # substring SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # length[i] shows the length of palindromic substring with center i SCREAMING_SNAKE_CASE =[1 for i in range(len(lowerCAmelCase_ ) )] # for each character in new_string find corresponding palindromic string SCREAMING_SNAKE_CASE =0 for j in range(len(lowerCAmelCase_ ) ): SCREAMING_SNAKE_CASE =1 if j > r else min(length[l + r - j] // 2, r - j + 1 ) while ( j - k >= 0 and j + k < len(lowerCAmelCase_ ) and new_input_string[k + j] == new_input_string[j - k] ): k += 1 SCREAMING_SNAKE_CASE =2 * k - 1 # does this string is ending after the previously explored end (that is r) ? # if yes the update the new r to the last index of this if j + k - 1 > r: SCREAMING_SNAKE_CASE =j - k + 1 # noqa: E741 SCREAMING_SNAKE_CASE =j + k - 1 # update max_length and start position if max_length < length[j]: SCREAMING_SNAKE_CASE =length[j] SCREAMING_SNAKE_CASE =j # create that string SCREAMING_SNAKE_CASE =new_input_string[start - max_length // 2 : start + max_length // 2 + 1] for i in s: if i != "|": output_string += i return output_string if __name__ == "__main__": import doctest doctest.testmod()
334
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
1
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
1
import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =RobertaPreLayerNormConfig.from_pretrained( lowerCAmelCase_, architectures=['RobertaPreLayerNormForMaskedLM'] ) # convert state_dict SCREAMING_SNAKE_CASE =torch.load(hf_hub_download(repo_id=lowerCAmelCase_, filename='pytorch_model.bin' ) ) SCREAMING_SNAKE_CASE ={} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('roberta.' ): SCREAMING_SNAKE_CASE ='roberta_prelayernorm.' + tensor_key[len('roberta.' ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('.self.LayerNorm.weight' ) or tensor_key.endswith('.self.LayerNorm.bias' ): continue SCREAMING_SNAKE_CASE =tensor_value SCREAMING_SNAKE_CASE =RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=lowerCAmelCase_, config=lowerCAmelCase_, state_dict=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) # convert tokenizer SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(lowerCAmelCase_ ) tokenizer.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint-repo", default=None, type=str, required=True, help="Path the official PyTorch dump, e.g. 'andreasmadsen/efficient_mlm_m0.40'.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) _lowerCamelCase =parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size 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 =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar _lowerCamelCase =TypeVar("KEY") _lowerCamelCase =TypeVar("VAL") @dataclass(frozen=lowerCamelCase_ , slots=lowerCamelCase_ ) class a_ ( Generic[KEY, VAL] ): """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 class a_ ( _Item ): """simple docstring""" def __init__( self : int ): super().__init__(snake_case ,snake_case ) def __bool__( self : Dict ): return False _lowerCamelCase =_DeletedItem() class a_ ( MutableMapping[KEY, VAL] ): """simple docstring""" def __init__( self : int ,snake_case : int = 8 ,snake_case : float = 0.75 ): SCREAMING_SNAKE_CASE =initial_block_size SCREAMING_SNAKE_CASE =[None] * initial_block_size assert 0.0 < capacity_factor < 1.0 SCREAMING_SNAKE_CASE =capacity_factor SCREAMING_SNAKE_CASE =0 def _lowerCAmelCase ( self : str ,snake_case : KEY ): return hash(snake_case ) % len(self._buckets ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : int ): return (ind + 1) % len(self._buckets ) def _lowerCAmelCase ( self : List[Any] ,snake_case : int ,snake_case : KEY ,snake_case : VAL ): SCREAMING_SNAKE_CASE =self._buckets[ind] if not stored: SCREAMING_SNAKE_CASE =_Item(snake_case ,snake_case ) self._len += 1 return True elif stored.key == key: SCREAMING_SNAKE_CASE =_Item(snake_case ,snake_case ) return True else: return False def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =len(self._buckets ) * self._capacity_factor return len(self ) >= int(snake_case ) def _lowerCAmelCase ( self : Dict ): if len(self._buckets ) <= self._initial_block_size: return False SCREAMING_SNAKE_CASE =len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def _lowerCAmelCase ( self : Any ,snake_case : int ): SCREAMING_SNAKE_CASE =self._buckets SCREAMING_SNAKE_CASE =[None] * new_size SCREAMING_SNAKE_CASE =0 for item in old_buckets: if item: self._add_item(item.key ,item.val ) def _lowerCAmelCase ( self : Any ): self._resize(len(self._buckets ) * 2 ) def _lowerCAmelCase ( self : Optional[Any] ): self._resize(len(self._buckets ) // 2 ) def _lowerCAmelCase ( self : List[Any] ,snake_case : KEY ): SCREAMING_SNAKE_CASE =self._get_bucket_index(snake_case ) for _ in range(len(self._buckets ) ): yield ind SCREAMING_SNAKE_CASE =self._get_next_ind(snake_case ) def _lowerCAmelCase ( self : str ,snake_case : KEY ,snake_case : VAL ): for ind in self._iterate_buckets(snake_case ): if self._try_set(snake_case ,snake_case ,snake_case ): break def __setitem__( self : Union[str, Any] ,snake_case : KEY ,snake_case : VAL ): if self._is_full(): self._size_up() self._add_item(snake_case ,snake_case ) def __delitem__( self : str ,snake_case : KEY ): for ind in self._iterate_buckets(snake_case ): SCREAMING_SNAKE_CASE =self._buckets[ind] if item is None: raise KeyError(snake_case ) if item is _deleted: continue if item.key == key: SCREAMING_SNAKE_CASE =_deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : int ,snake_case : KEY ): for ind in self._iterate_buckets(snake_case ): SCREAMING_SNAKE_CASE =self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(snake_case ) def __len__( self : Optional[Any] ): return self._len def __iter__( self : List[str] ): yield from (item.key for item in self._buckets if item) def __repr__( self : Tuple ): SCREAMING_SNAKE_CASE =' ,'.join( f'{item.key}: {item.val}' for item in self._buckets if item ) return f'HashMap({val_string})'
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowerCamelCase ={ "configuration_mask2former": [ "MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "Mask2FormerConfig", ], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["Mask2FormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_maskaformer import MASK2FORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskaFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_maskaformer import MaskaFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskaformer import ( MASK2FORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskaFormerForUniversalSegmentation, MaskaFormerModel, MaskaFormerPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure)
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
import unittest from transformers import BertGenerationTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase ="▁" _lowerCamelCase =get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece class a_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = BertGenerationTokenizer __UpperCAmelCase = False __UpperCAmelCase = True def _lowerCAmelCase ( self : Optional[int] ): super().setUp() SCREAMING_SNAKE_CASE =BertGenerationTokenizer(snake_case ,keep_accents=snake_case ) tokenizer.save_pretrained(self.tmpdirname ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE ='<s>' SCREAMING_SNAKE_CASE =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case ) ,snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case ) ,snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<unk>' ) self.assertEqual(vocab_keys[1] ,'<s>' ) self.assertEqual(vocab_keys[-1] ,'<pad>' ) self.assertEqual(len(snake_case ) ,1002 ) def _lowerCAmelCase ( self : Optional[int] ): self.assertEqual(self.get_tokenizer().vocab_size ,1000 ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =BertGenerationTokenizer(snake_case ,keep_accents=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.tokenize('This is a test' ) self.assertListEqual(snake_case ,['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(snake_case ) ,[285, 46, 10, 170, 382] ,) SCREAMING_SNAKE_CASE =tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( snake_case ,[ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] ,) SCREAMING_SNAKE_CASE =tokenizer.convert_tokens_to_ids(snake_case ) self.assertListEqual( snake_case ,[8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ,) SCREAMING_SNAKE_CASE =tokenizer.convert_ids_to_tokens(snake_case ) self.assertListEqual( snake_case ,[ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] ,) @cached_property def _lowerCAmelCase ( self : Any ): return BertGenerationTokenizer.from_pretrained('google/bert_for_seq_generation_L-24_bbc_encoder' ) @slow def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE ='Hello World!' SCREAMING_SNAKE_CASE =[18536, 2260, 101] self.assertListEqual(snake_case ,self.big_tokenizer.encode(snake_case ) ) @slow def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) SCREAMING_SNAKE_CASE =[ 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, ] self.assertListEqual(snake_case ,self.big_tokenizer.encode(snake_case ) ) @require_torch @slow def _lowerCAmelCase ( self : List[Any] ): import torch from transformers import BertGenerationConfig, BertGenerationEncoder # Build sequence SCREAMING_SNAKE_CASE =list(self.big_tokenizer.get_vocab().keys() )[:10] SCREAMING_SNAKE_CASE =' '.join(snake_case ) SCREAMING_SNAKE_CASE =self.big_tokenizer.encode_plus(snake_case ,return_tensors='pt' ,return_token_type_ids=snake_case ) SCREAMING_SNAKE_CASE =self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] ,return_tensors='pt' ,return_token_type_ids=snake_case ) SCREAMING_SNAKE_CASE =BertGenerationConfig() SCREAMING_SNAKE_CASE =BertGenerationEncoder(snake_case ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**snake_case ) model(**snake_case ) @slow def _lowerCAmelCase ( self : Optional[Any] ): # fmt: off SCREAMING_SNAKE_CASE ={'input_ids': [[39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114], [448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=snake_case ,model_name='google/bert_for_seq_generation_L-24_bbc_encoder' ,revision='c817d1fd1be2ffa69431227a1fe320544943d4db' ,)
334
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 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 =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_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.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , 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 a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : 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(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : 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(snake_case ) 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] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError('String lengths must match!' ) SCREAMING_SNAKE_CASE =0 for chara, chara in zip(lowerCAmelCase_, lowerCAmelCase_ ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "vocab_file": "vocab.json", "merges_file": "merges.txt", } _lowerCamelCase ={ "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"}, "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"}, } _lowerCamelCase ={ "ctrl": 2_56, } _lowerCamelCase ={ "Pregnancy": 16_86_29, "Christianity": 76_75, "Explain": 10_64_23, "Fitness": 6_34_40, "Saving": 6_31_63, "Ask": 2_71_71, "Ass": 9_59_85, "Joke": 16_35_09, "Questions": 4_56_22, "Thoughts": 4_96_05, "Retail": 5_23_42, "Feminism": 16_43_38, "Writing": 1_19_92, "Atheism": 19_22_63, "Netflix": 4_86_16, "Computing": 3_96_39, "Opinion": 4_32_13, "Alone": 4_49_67, "Funny": 5_89_17, "Gaming": 4_03_58, "Human": 40_88, "India": 13_31, "Joker": 7_71_38, "Diet": 3_62_06, "Legal": 1_18_59, "Norman": 49_39, "Tip": 7_26_89, "Weight": 5_23_43, "Movies": 4_62_73, "Running": 2_34_25, "Science": 20_90, "Horror": 3_77_93, "Confession": 6_05_72, "Finance": 1_22_50, "Politics": 1_63_60, "Scary": 19_19_85, "Support": 1_26_54, "Technologies": 3_25_16, "Teenage": 6_61_60, "Event": 3_27_69, "Learned": 6_74_60, "Notion": 18_27_70, "Wikipedia": 3_75_83, "Books": 66_65, "Extract": 7_60_50, "Confessions": 10_27_01, "Conspiracy": 7_59_32, "Links": 6_36_74, "Narcissus": 15_04_25, "Relationship": 5_47_66, "Relationships": 13_47_96, "Reviews": 4_16_71, "News": 42_56, "Translation": 2_68_20, "multilingual": 12_84_06, } def snake_case__ ( 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 SCREAMING_SNAKE_CASE =set(lowerCAmelCase_ ) return pairs class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = CONTROL_CODES def __init__( self : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : Any="<unk>" ,**snake_case : Any ): super().__init__(unk_token=snake_case ,**snake_case ) with open(snake_case ,encoding='utf-8' ) as vocab_handle: SCREAMING_SNAKE_CASE =json.load(snake_case ) SCREAMING_SNAKE_CASE ={v: k for k, v in self.encoder.items()} with open(snake_case ,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 merges] SCREAMING_SNAKE_CASE =dict(zip(snake_case ,range(len(snake_case ) ) ) ) SCREAMING_SNAKE_CASE ={} @property def _lowerCAmelCase ( self : List[str] ): return len(self.encoder ) def _lowerCAmelCase ( self : str ): return dict(self.encoder ,**self.added_tokens_encoder ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Union[str, Any] ): if token in self.cache: return self.cache[token] SCREAMING_SNAKE_CASE =tuple(snake_case ) SCREAMING_SNAKE_CASE =tuple(list(word[:-1] ) + [word[-1] + '</w>'] ) SCREAMING_SNAKE_CASE =get_pairs(snake_case ) if not pairs: return token while True: SCREAMING_SNAKE_CASE =min(snake_case ,key=lambda snake_case : self.bpe_ranks.get(snake_case ,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(snake_case ): try: SCREAMING_SNAKE_CASE =word.index(snake_case ,snake_case ) 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(snake_case ) - 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(snake_case ) SCREAMING_SNAKE_CASE =new_word if len(snake_case ) == 1: break else: SCREAMING_SNAKE_CASE =get_pairs(snake_case ) SCREAMING_SNAKE_CASE ='@@ '.join(snake_case ) SCREAMING_SNAKE_CASE =word[:-4] SCREAMING_SNAKE_CASE =word return word def _lowerCAmelCase ( self : Tuple ,snake_case : int ): SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =re.findall(r'\S+\n?' ,snake_case ) for token in words: split_tokens.extend(list(self.bpe(snake_case ).split(' ' ) ) ) return split_tokens def _lowerCAmelCase ( self : int ,snake_case : Union[str, Any] ): return self.encoder.get(snake_case ,self.encoder.get(self.unk_token ) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Optional[Any] ): return self.decoder.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =' '.join(snake_case ).replace('@@ ' ,'' ).strip() return out_string def _lowerCAmelCase ( self : int ,snake_case : str ,snake_case : Optional[str] = None ): if not os.path.isdir(snake_case ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return SCREAMING_SNAKE_CASE =os.path.join( snake_case ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE =os.path.join( snake_case ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(snake_case ,'w' ,encoding='utf-8' ) as f: f.write(json.dumps(self.encoder ,indent=2 ,sort_keys=snake_case ,ensure_ascii=snake_case ) + '\n' ) SCREAMING_SNAKE_CASE =0 with open(snake_case ,'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 snake_case : 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(snake_case ) + '\n' ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
334
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 # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( 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 _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( 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 snake_case__ ( ): """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()
334
1
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = (PNDMScheduler,) __UpperCAmelCase = (('num_inference_steps', 50),) def _lowerCAmelCase ( self : Tuple ,**snake_case : List[Any] ): SCREAMING_SNAKE_CASE ={ 'num_train_timesteps': 1000, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', } config.update(**snake_case ) return config def _lowerCAmelCase ( self : str ,snake_case : Tuple=0 ,**snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE =kwargs.pop('num_inference_steps' ,snake_case ) SCREAMING_SNAKE_CASE =self.dummy_sample SCREAMING_SNAKE_CASE =0.1 * sample SCREAMING_SNAKE_CASE =[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE =self.get_scheduler_config(**snake_case ) SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) scheduler.set_timesteps(snake_case ) # copy over dummy past residuals SCREAMING_SNAKE_CASE =dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(snake_case ) SCREAMING_SNAKE_CASE =scheduler_class.from_pretrained(snake_case ) new_scheduler.set_timesteps(snake_case ) # copy over dummy past residuals SCREAMING_SNAKE_CASE =dummy_past_residuals[:] SCREAMING_SNAKE_CASE =scheduler.step_prk(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample SCREAMING_SNAKE_CASE =new_scheduler.step_prk(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE =scheduler.step_plms(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample SCREAMING_SNAKE_CASE =new_scheduler.step_plms(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _lowerCAmelCase ( self : Optional[int] ): pass def _lowerCAmelCase ( self : Dict ,snake_case : List[str]=0 ,**snake_case : Dict ): SCREAMING_SNAKE_CASE =dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE =kwargs.pop('num_inference_steps' ,snake_case ) SCREAMING_SNAKE_CASE =self.dummy_sample SCREAMING_SNAKE_CASE =0.1 * sample SCREAMING_SNAKE_CASE =[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE =self.get_scheduler_config() SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) scheduler.set_timesteps(snake_case ) # copy over dummy past residuals (must be after setting timesteps) SCREAMING_SNAKE_CASE =dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(snake_case ) SCREAMING_SNAKE_CASE =scheduler_class.from_pretrained(snake_case ) # copy over dummy past residuals new_scheduler.set_timesteps(snake_case ) # copy over dummy past residual (must be after setting timesteps) SCREAMING_SNAKE_CASE =dummy_past_residuals[:] SCREAMING_SNAKE_CASE =scheduler.step_prk(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample SCREAMING_SNAKE_CASE =new_scheduler.step_prk(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" SCREAMING_SNAKE_CASE =scheduler.step_plms(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample SCREAMING_SNAKE_CASE =new_scheduler.step_plms(snake_case ,snake_case ,snake_case ,**snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def _lowerCAmelCase ( self : Optional[Any] ,**snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =self.scheduler_classes[0] SCREAMING_SNAKE_CASE =self.get_scheduler_config(**snake_case ) SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) SCREAMING_SNAKE_CASE =10 SCREAMING_SNAKE_CASE =self.dummy_model() SCREAMING_SNAKE_CASE =self.dummy_sample_deter scheduler.set_timesteps(snake_case ) for i, t in enumerate(scheduler.prk_timesteps ): SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =scheduler.step_prk(snake_case ,snake_case ,snake_case ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =scheduler.step_plms(snake_case ,snake_case ,snake_case ).prev_sample return sample def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =dict(self.forward_default_kwargs ) SCREAMING_SNAKE_CASE =kwargs.pop('num_inference_steps' ,snake_case ) for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE =self.get_scheduler_config() SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) SCREAMING_SNAKE_CASE =self.dummy_sample SCREAMING_SNAKE_CASE =0.1 * sample if num_inference_steps is not None and hasattr(snake_case ,'set_timesteps' ): scheduler.set_timesteps(snake_case ) elif num_inference_steps is not None and not hasattr(snake_case ,'set_timesteps' ): SCREAMING_SNAKE_CASE =num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) SCREAMING_SNAKE_CASE =[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] SCREAMING_SNAKE_CASE =dummy_past_residuals[:] SCREAMING_SNAKE_CASE =scheduler.step_prk(snake_case ,0 ,snake_case ,**snake_case ).prev_sample SCREAMING_SNAKE_CASE =scheduler.step_prk(snake_case ,1 ,snake_case ,**snake_case ).prev_sample self.assertEqual(output_a.shape ,sample.shape ) self.assertEqual(output_a.shape ,output_a.shape ) SCREAMING_SNAKE_CASE =scheduler.step_plms(snake_case ,0 ,snake_case ,**snake_case ).prev_sample SCREAMING_SNAKE_CASE =scheduler.step_plms(snake_case ,1 ,snake_case ,**snake_case ).prev_sample self.assertEqual(output_a.shape ,sample.shape ) self.assertEqual(output_a.shape ,output_a.shape ) def _lowerCAmelCase ( self : str ): for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=snake_case ) def _lowerCAmelCase ( self : List[str] ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=snake_case ) SCREAMING_SNAKE_CASE =self.scheduler_classes[0] SCREAMING_SNAKE_CASE =self.get_scheduler_config(steps_offset=1 ) SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps ,torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) ,) def _lowerCAmelCase ( self : List[Any] ): for beta_start, beta_end in zip([0.0_001, 0.001] ,[0.002, 0.02] ): self.check_over_configs(beta_start=snake_case ,beta_end=snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=snake_case ) def _lowerCAmelCase ( self : List[Any] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=snake_case ) def _lowerCAmelCase ( self : Tuple ): for t in [1, 5, 10]: self.check_over_forward(time_step=snake_case ) def _lowerCAmelCase ( self : Dict ): for t, num_inference_steps in zip([1, 5, 10] ,[10, 50, 100] ): self.check_over_forward(num_inference_steps=snake_case ) def _lowerCAmelCase ( self : List[str] ): # earlier version of set_timesteps() caused an error indexing alpha's with inference steps as power of 3 SCREAMING_SNAKE_CASE =27 for scheduler_class in self.scheduler_classes: SCREAMING_SNAKE_CASE =self.dummy_sample SCREAMING_SNAKE_CASE =0.1 * sample SCREAMING_SNAKE_CASE =self.get_scheduler_config() SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) scheduler.set_timesteps(snake_case ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): SCREAMING_SNAKE_CASE =scheduler.step_prk(snake_case ,snake_case ,snake_case ).prev_sample def _lowerCAmelCase ( self : Tuple ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =self.scheduler_classes[0] SCREAMING_SNAKE_CASE =self.get_scheduler_config() SCREAMING_SNAKE_CASE =scheduler_class(**snake_case ) scheduler.step_plms(self.dummy_sample ,1 ,self.dummy_sample ).prev_sample def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.full_loop() SCREAMING_SNAKE_CASE =torch.sum(torch.abs(snake_case ) ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_sum.item() - 198.1_318 ) < 1e-2 assert abs(result_mean.item() - 0.2_580 ) < 1e-3 def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.full_loop(prediction_type='v_prediction' ) SCREAMING_SNAKE_CASE =torch.sum(torch.abs(snake_case ) ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_sum.item() - 67.3_986 ) < 1e-2 assert abs(result_mean.item() - 0.0_878 ) < 1e-3 def _lowerCAmelCase ( self : List[Any] ): # We specify different beta, so that the first alpha is 0.99 SCREAMING_SNAKE_CASE =self.full_loop(set_alpha_to_one=snake_case ,beta_start=0.01 ) SCREAMING_SNAKE_CASE =torch.sum(torch.abs(snake_case ) ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_sum.item() - 230.0_399 ) < 1e-2 assert abs(result_mean.item() - 0.2_995 ) < 1e-3 def _lowerCAmelCase ( self : List[Any] ): # We specify different beta, so that the first alpha is 0.99 SCREAMING_SNAKE_CASE =self.full_loop(set_alpha_to_one=snake_case ,beta_start=0.01 ) SCREAMING_SNAKE_CASE =torch.sum(torch.abs(snake_case ) ) SCREAMING_SNAKE_CASE =torch.mean(torch.abs(snake_case ) ) assert abs(result_sum.item() - 186.9_482 ) < 1e-2 assert abs(result_mean.item() - 0.2_434 ) < 1e-3
334
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase ={"configuration_plbart": ["PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "PLBartConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["PLBartTokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "PLBART_PRETRAINED_MODEL_ARCHIVE_LIST", "PLBartForCausalLM", "PLBartForConditionalGeneration", "PLBartForSequenceClassification", "PLBartModel", "PLBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure)
334
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) for i in range(length - 1 ): SCREAMING_SNAKE_CASE =i for k in range(i + 1, lowerCAmelCase_ ): if collection[k] < collection[least]: SCREAMING_SNAKE_CASE =k if least != i: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =(collection[i], collection[least]) return collection if __name__ == "__main__": _lowerCamelCase =input("Enter numbers separated by a comma:\n").strip() _lowerCamelCase =[int(item) for item in user_input.split(",")] print(selection_sort(unsorted))
334
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size 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 SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": 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(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) 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 =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
1
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging _lowerCamelCase =logging.get_logger(__name__) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =set() SCREAMING_SNAKE_CASE =[] def parse_line(lowerCAmelCase_ ): for line in fp: if isinstance(lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =line.decode('UTF-8' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(' ' ): # process a single warning and move it to `selected_warnings`. if len(lowerCAmelCase_ ) > 0: SCREAMING_SNAKE_CASE ='\n'.join(lowerCAmelCase_ ) # Only keep the warnings specified in `targets` if any(F': {x}: ' in warning for x in targets ): selected_warnings.add(lowerCAmelCase_ ) buffer.clear() continue else: SCREAMING_SNAKE_CASE =line.strip() buffer.append(lowerCAmelCase_ ) if from_gh: for filename in os.listdir(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, lowerCAmelCase_ ) if not os.path.isdir(lowerCAmelCase_ ): # read the file if filename != "warnings.txt": continue with open(lowerCAmelCase_ ) as fp: parse_line(lowerCAmelCase_ ) else: try: with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file if filename != "warnings.txt": continue with z.open(lowerCAmelCase_ ) as fp: parse_line(lowerCAmelCase_ ) except Exception: logger.warning( F'{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.' ) return selected_warnings def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =set() SCREAMING_SNAKE_CASE =[os.path.join(lowerCAmelCase_, lowerCAmelCase_ ) for p in os.listdir(lowerCAmelCase_ ) if (p.endswith('.zip' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(lowerCAmelCase_, lowerCAmelCase_ ) ) return selected_warnings if __name__ == "__main__": def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return values.split(',' ) _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") # optional parameters parser.add_argument( "--targets", default="DeprecationWarning,UserWarning,FutureWarning", type=list_str, help="Comma-separated list of target warning(s) which we want to extract.", ) parser.add_argument( "--from_gh", action="store_true", help="If running from a GitHub action workflow and collecting warnings from its artifacts.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links _lowerCamelCase =get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("=" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts _lowerCamelCase =extract_warnings(args.output_dir, args.targets) _lowerCamelCase =sorted(selected_warnings) with open(os.path.join(args.output_dir, "selected_warnings.json"), "w", encoding="UTF-8") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot import BlenderbotTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } _lowerCamelCase ={ "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"}, "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"}, "tokenizer_config_file": { "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json" }, } _lowerCamelCase ={"facebook/blenderbot-3B": 1_28} class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] __UpperCAmelCase = BlenderbotTokenizer def __init__( self : Tuple ,snake_case : Optional[Any]=None ,snake_case : List[str]=None ,snake_case : Dict=None ,snake_case : str="replace" ,snake_case : Tuple="<s>" ,snake_case : List[Any]="</s>" ,snake_case : Any="</s>" ,snake_case : Optional[int]="<s>" ,snake_case : Tuple="<unk>" ,snake_case : Dict="<pad>" ,snake_case : List[Any]="<mask>" ,snake_case : Dict=False ,snake_case : List[Any]=True ,**snake_case : int ,): super().__init__( snake_case ,snake_case ,tokenizer_file=snake_case ,errors=snake_case ,bos_token=snake_case ,eos_token=snake_case ,sep_token=snake_case ,cls_token=snake_case ,unk_token=snake_case ,pad_token=snake_case ,mask_token=snake_case ,add_prefix_space=snake_case ,trim_offsets=snake_case ,**snake_case ,) SCREAMING_SNAKE_CASE =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' ,snake_case ) != add_prefix_space: SCREAMING_SNAKE_CASE =getattr(snake_case ,pre_tok_state.pop('type' ) ) SCREAMING_SNAKE_CASE =add_prefix_space SCREAMING_SNAKE_CASE =pre_tok_class(**snake_case ) SCREAMING_SNAKE_CASE =add_prefix_space SCREAMING_SNAKE_CASE ='post_processor' SCREAMING_SNAKE_CASE =getattr(self.backend_tokenizer ,snake_case ,snake_case ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE =json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE =tuple(state['sep'] ) if "cls" in state: SCREAMING_SNAKE_CASE =tuple(state['cls'] ) SCREAMING_SNAKE_CASE =False if state.get('add_prefix_space' ,snake_case ) != add_prefix_space: SCREAMING_SNAKE_CASE =add_prefix_space SCREAMING_SNAKE_CASE =True if state.get('trim_offsets' ,snake_case ) != trim_offsets: SCREAMING_SNAKE_CASE =trim_offsets SCREAMING_SNAKE_CASE =True if changes_to_apply: SCREAMING_SNAKE_CASE =getattr(snake_case ,state.pop('type' ) ) SCREAMING_SNAKE_CASE =component_class(**snake_case ) setattr(self.backend_tokenizer ,snake_case ,snake_case ) @property # Copied from transformers.models.roberta.tokenization_roberta_fast.RobertaTokenizerFast.mask_token with Roberta->Blenderbot, RoBERTa->Blenderbot def _lowerCAmelCase ( self : Optional[int] ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def _lowerCAmelCase ( self : str ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =AddedToken(snake_case ,lstrip=snake_case ,rstrip=snake_case ) if isinstance(snake_case ,snake_case ) else value SCREAMING_SNAKE_CASE =value def _lowerCAmelCase ( self : Optional[Any] ,*snake_case : Optional[Any] ,**snake_case : List[str] ): SCREAMING_SNAKE_CASE =kwargs.get('is_split_into_words' ,snake_case ) assert self.add_prefix_space or not is_split_into_words, ( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*snake_case ,**snake_case ) def _lowerCAmelCase ( self : Tuple ,*snake_case : List[Any] ,**snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =kwargs.get('is_split_into_words' ,snake_case ) assert self.add_prefix_space or not is_split_into_words, ( f'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*snake_case ,**snake_case ) def _lowerCAmelCase ( self : List[Any] ,snake_case : str ,snake_case : Optional[str] = None ): SCREAMING_SNAKE_CASE =self._tokenizer.model.save(snake_case ,name=snake_case ) return tuple(snake_case ) def _lowerCAmelCase ( self : str ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): 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 _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): return token_ids_a + [self.eos_token_id] def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : "Conversation" ): SCREAMING_SNAKE_CASE =[] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(' ' + text ) else: # Generated responses should contain them already. inputs.append(snake_case ) SCREAMING_SNAKE_CASE =' '.join(snake_case ) SCREAMING_SNAKE_CASE =self.encode(snake_case ) if len(snake_case ) > self.model_max_length: SCREAMING_SNAKE_CASE =input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) 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 =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
1
from typing import Dict, Optional import numpy as np import datasets _lowerCamelCase ="\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n" _lowerCamelCase ="\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric(\"mean_iou\")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {'mean_iou': 0.47750000000000004, 'mean_accuracy': 0.5916666666666666, 'overall_accuracy': 0.5263157894736842, 'per_category_iou': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), 'per_category_accuracy': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n" _lowerCamelCase ="\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}" def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = False, ): """simple docstring""" if label_map is not None: for old_id, new_id in label_map.items(): SCREAMING_SNAKE_CASE =new_id # turn into Numpy arrays SCREAMING_SNAKE_CASE =np.array(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.array(lowerCAmelCase_ ) if reduce_labels: SCREAMING_SNAKE_CASE =255 SCREAMING_SNAKE_CASE =label - 1 SCREAMING_SNAKE_CASE =255 SCREAMING_SNAKE_CASE =label != ignore_index SCREAMING_SNAKE_CASE =np.not_equal(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pred_label[mask] SCREAMING_SNAKE_CASE =np.array(lowerCAmelCase_ )[mask] SCREAMING_SNAKE_CASE =pred_label[pred_label == label] SCREAMING_SNAKE_CASE =np.histogram(lowerCAmelCase_, bins=lowerCAmelCase_, range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE =np.histogram(lowerCAmelCase_, bins=lowerCAmelCase_, range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE =np.histogram(lowerCAmelCase_, bins=lowerCAmelCase_, range=(0, num_labels - 1) )[0] SCREAMING_SNAKE_CASE =area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = False, ): """simple docstring""" SCREAMING_SNAKE_CASE =np.zeros((num_labels,), dtype=np.floataa ) SCREAMING_SNAKE_CASE =np.zeros((num_labels,), dtype=np.floataa ) SCREAMING_SNAKE_CASE =np.zeros((num_labels,), dtype=np.floataa ) SCREAMING_SNAKE_CASE =np.zeros((num_labels,), dtype=np.floataa ) for result, gt_seg_map in zip(lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =intersect_and_union( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = None, lowerCAmelCase_ = False, ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =total_intersect_and_union( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) # compute metrics SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =total_area_intersect.sum() / total_area_label.sum() SCREAMING_SNAKE_CASE =total_area_intersect / total_area_union SCREAMING_SNAKE_CASE =total_area_intersect / total_area_label SCREAMING_SNAKE_CASE =np.nanmean(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.nanmean(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =all_acc SCREAMING_SNAKE_CASE =iou SCREAMING_SNAKE_CASE =acc if nan_to_num is not None: SCREAMING_SNAKE_CASE ={metric: np.nan_to_num(lowerCAmelCase_, nan=lowerCAmelCase_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : str ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { 'predictions': datasets.Sequence(datasets.Sequence(datasets.Value('uint16' ) ) ), 'references': datasets.Sequence(datasets.Sequence(datasets.Value('uint16' ) ) ), } ) ,reference_urls=[ 'https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py' ] ,) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : Optional[int] ,snake_case : int ,snake_case : bool ,snake_case : Optional[int] = None ,snake_case : Optional[Dict[int, int]] = None ,snake_case : bool = False ,): SCREAMING_SNAKE_CASE =mean_iou( results=snake_case ,gt_seg_maps=snake_case ,num_labels=snake_case ,ignore_index=snake_case ,nan_to_num=snake_case ,label_map=snake_case ,reduce_labels=snake_case ,) return iou_result
334
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
1
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py _lowerCamelCase ="src/diffusers" _lowerCamelCase ="." # This is to make sure the diffusers module imported is the one in the repo. _lowerCamelCase =importlib.util.spec_from_file_location( "diffusers", os.path.join(DIFFUSERS_PATH, "__init__.py"), submodule_search_locations=[DIFFUSERS_PATH], ) _lowerCamelCase =spec.loader.load_module() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return line.startswith(lowerCAmelCase_ ) or len(lowerCAmelCase_ ) <= 1 or re.search(r'^\s*\)(\s*->.*:|:)\s*$', lowerCAmelCase_ ) is not None def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =object_name.split('.' ) SCREAMING_SNAKE_CASE =0 # First let's find the module where our object lives. SCREAMING_SNAKE_CASE =parts[i] while i < len(lowerCAmelCase_ ) and not os.path.isfile(os.path.join(lowerCAmelCase_, F'{module}.py' ) ): i += 1 if i < len(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, parts[i] ) if i >= len(lowerCAmelCase_ ): raise ValueError(F'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(lowerCAmelCase_, F'{module}.py' ), 'r', encoding='utf-8', newline='\n' ) as f: SCREAMING_SNAKE_CASE =f.readlines() # Now let's find the class / func in the code! SCREAMING_SNAKE_CASE ='' SCREAMING_SNAKE_CASE =0 for name in parts[i + 1 :]: while ( line_index < len(lowerCAmelCase_ ) and re.search(rF'^{indent}(class|def)\s+{name}(\(|\:)', lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(lowerCAmelCase_ ): raise ValueError(F' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). SCREAMING_SNAKE_CASE =line_index while line_index < len(lowerCAmelCase_ ) and _should_continue(lines[line_index], lowerCAmelCase_ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 SCREAMING_SNAKE_CASE =lines[start_index:line_index] return "".join(lowerCAmelCase_ ) _lowerCamelCase =re.compile(R"^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)") _lowerCamelCase =re.compile(R"^\s*(\S+)->(\S+)(\s+.*|$)") _lowerCamelCase =re.compile(R"<FILL\s+[^>]*>") def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =code.split('\n' ) SCREAMING_SNAKE_CASE =0 while idx < len(lowerCAmelCase_ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(lowerCAmelCase_ ): return re.search(r'^(\s*)\S', lines[idx] ).groups()[0] return "" def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len(get_indent(lowerCAmelCase_ ) ) > 0 if has_indent: SCREAMING_SNAKE_CASE =F'class Bla:\n{code}' SCREAMING_SNAKE_CASE =black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=119, preview=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =black.format_str(lowerCAmelCase_, mode=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =style_docstrings_in_code(lowerCAmelCase_ ) return result[len('class Bla:\n' ) :] if has_indent else result def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=False ): """simple docstring""" with open(lowerCAmelCase_, 'r', encoding='utf-8', newline='\n' ) as f: SCREAMING_SNAKE_CASE =f.readlines() SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =_re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =search.groups() SCREAMING_SNAKE_CASE =find_code_in_diffusers(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_indent(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =line_index + 1 if indent == theoretical_indent else line_index + 2 SCREAMING_SNAKE_CASE =theoretical_indent SCREAMING_SNAKE_CASE =start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. SCREAMING_SNAKE_CASE =True while line_index < len(lowerCAmelCase_ ) and should_continue: line_index += 1 if line_index >= len(lowerCAmelCase_ ): break SCREAMING_SNAKE_CASE =lines[line_index] SCREAMING_SNAKE_CASE =_should_continue(lowerCAmelCase_, lowerCAmelCase_ ) and re.search(F'^{indent}# End copy', lowerCAmelCase_ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 SCREAMING_SNAKE_CASE =lines[start_index:line_index] SCREAMING_SNAKE_CASE =''.join(lowerCAmelCase_ ) # Remove any nested `Copied from` comments to avoid circular copies SCREAMING_SNAKE_CASE =[line for line in theoretical_code.split('\n' ) if _re_copy_warning.search(lowerCAmelCase_ ) is None] SCREAMING_SNAKE_CASE ='\n'.join(lowerCAmelCase_ ) # Before comparing, use the `replace_pattern` on the original code. if len(lowerCAmelCase_ ) > 0: SCREAMING_SNAKE_CASE =replace_pattern.replace('with', '' ).split(',' ) SCREAMING_SNAKE_CASE =[_re_replace_pattern.search(lowerCAmelCase_ ) for p in patterns] for pattern in patterns: if pattern is None: continue SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =pattern.groups() SCREAMING_SNAKE_CASE =re.sub(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) if option.strip() == "all-casing": SCREAMING_SNAKE_CASE =re.sub(obja.lower(), obja.lower(), lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =re.sub(obja.upper(), obja.upper(), lowerCAmelCase_ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line SCREAMING_SNAKE_CASE =blackify(lines[start_index - 1] + theoretical_code ) SCREAMING_SNAKE_CASE =theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: SCREAMING_SNAKE_CASE =lines[:start_index] + [theoretical_code] + lines[line_index:] SCREAMING_SNAKE_CASE =start_index + 1 if overwrite and len(lowerCAmelCase_ ) > 0: # Warn the user a file has been modified. print(F'Detected changes, rewriting {filename}.' ) with open(lowerCAmelCase_, 'w', encoding='utf-8', newline='\n' ) as f: f.writelines(lowerCAmelCase_ ) return diffs def snake_case__ ( lowerCAmelCase_ = False ): """simple docstring""" SCREAMING_SNAKE_CASE =glob.glob(os.path.join(lowerCAmelCase_, '**/*.py' ), recursive=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =[] for filename in all_files: SCREAMING_SNAKE_CASE =is_copy_consistent(lowerCAmelCase_, lowerCAmelCase_ ) diffs += [F'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(lowerCAmelCase_ ) > 0: SCREAMING_SNAKE_CASE ='\n'.join(lowerCAmelCase_ ) raise Exception( 'Found the following copy inconsistencies:\n' + diff + '\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.' ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _lowerCamelCase =parser.parse_args() check_copies(args.fix_and_overwrite)
334
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: writer.write({'col_1': 'foo', 'col_2': 1}, key=1 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=2 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =value @pytest.mark.parametrize('optimized_int_type, expected_dtype', [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype', [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ], ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
1
import random def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =num - 1 SCREAMING_SNAKE_CASE =0 while s % 2 == 0: SCREAMING_SNAKE_CASE =s // 2 t += 1 for _ in range(5 ): SCREAMING_SNAKE_CASE =random.randrange(2, num - 1 ) SCREAMING_SNAKE_CASE =pow(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) if v != 1: SCREAMING_SNAKE_CASE =0 while v != (num - 1): if i == t - 1: return False else: SCREAMING_SNAKE_CASE =i + 1 SCREAMING_SNAKE_CASE =(v**2) % num return True def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if num < 2: return False SCREAMING_SNAKE_CASE =[ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_ = 1024 ): """simple docstring""" while True: SCREAMING_SNAKE_CASE =random.randrange(2 ** (keysize - 1), 2 ** (keysize) ) if is_prime_low_num(lowerCAmelCase_ ): return num if __name__ == "__main__": _lowerCamelCase =generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
334
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase ={ "configuration_clipseg": [ "CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP", "CLIPSegConfig", "CLIPSegTextConfig", "CLIPSegVisionConfig", ], "processing_clipseg": ["CLIPSegProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST", "CLIPSegModel", "CLIPSegPreTrainedModel", "CLIPSegTextModel", "CLIPSegVisionModel", "CLIPSegForImageSegmentation", ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
1
from __future__ import annotations from math import pow, sqrt def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance == 0: return {"resistance": sqrt(pow(lowerCAmelCase_, 2 ) - pow(lowerCAmelCase_, 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(lowerCAmelCase_, 2 ) - pow(lowerCAmelCase_, 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(lowerCAmelCase_, 2 ) + pow(lowerCAmelCase_, 2 ) )} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate _lowerCamelCase =TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow("", "|", "|"), datarow=DataRow("", "|", "|"), padding=1, with_header_hide=None, ) _lowerCamelCase =[] _lowerCamelCase =[] _lowerCamelCase ={"type": "section", "text": {"type": "plain_text", "text": "No failed tests! 🤗", "emoji": True}} _lowerCamelCase =[ { "type": "header", "text": { "type": "plain_text", "text": f'🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results', "emoji": True, }, } ] _lowerCamelCase =0 for log in Path().glob("*.log"): _lowerCamelCase =0 with open(log, "r") as f: for line in f: _lowerCamelCase =json.loads(line) if line.get("nodeid", "") != "": _lowerCamelCase =line["nodeid"] if line.get("duration", None) is not None: _lowerCamelCase =f'{line["duration"]:.4f}' if line.get("outcome", "") == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split("_")[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) _lowerCamelCase =[] log.unlink() _lowerCamelCase ="" _lowerCamelCase =[] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += f"*{name[1:]}: {num_failed} failed test*\n" else: message += f"*{name[1:]}: {num_failed} failed tests*\n" _lowerCamelCase =[] _lowerCamelCase ={} for test in failed_tests: _lowerCamelCase =test[0].split("::") _lowerCamelCase =data[0].split("/")[-1] if data[0] not in filesafailed: _lowerCamelCase =[data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) _lowerCamelCase =[test[0] for test in failed_table] _lowerCamelCase =list(set(files)) # Count number of instances in failed_tests _lowerCamelCase =[] for file in individual_files: table.append([file, len(filesafailed[file])]) _lowerCamelCase =tabulate( table, headers=["Test Location", "Num Failed"], tablefmt=hf_table_format, stralign="right", ) message += f"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 30_00: _lowerCamelCase ="Too many failed tests, please see the full report in the Action results." _lowerCamelCase =len(err) + 10 _lowerCamelCase =message[: 30_00 - offset] + f'\n...\n```\n{err}' print(f'### {message}') else: _lowerCamelCase ="No failed tests! 🤗" print(f'## {message}') payload.append(no_error_payload) if os.environ.get("TEST_TYPE", "") != "": from slack_sdk import WebClient _lowerCamelCase =WebClient(token=os.environ["SLACK_API_TOKEN"]) if message != "No failed tests! 🤗": _lowerCamelCase ={ "type": "section", "text": { "type": "mrkdwn", "text": message, }, } payload.append(md_report) _lowerCamelCase ={ "type": "section", "text": { "type": "mrkdwn", "text": "*For more details:*", }, "accessory": { "type": "button", "text": { "type": "plain_text", "text": "Check Action results", "emoji": True, }, "url": f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } payload.append(action_button) _lowerCamelCase ={ "type": "context", "elements": [ { "type": "plain_text", "text": f'Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}', } ], } payload.append(date_report) _lowerCamelCase =client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload) _lowerCamelCase =response.data["ts"] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name _lowerCamelCase ="" for i, row in enumerate(test_failures): if row[0] != test_class: _lowerCamelCase =row[0] else: _lowerCamelCase ="" _lowerCamelCase ={ "type": "section", "text": { "type": "mrkdwn", "text": f'Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```', }, } client.chat_postMessage( channel="#accelerate-ci-daily", thread_ts=ts, blocks=[payload], )
334
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
1
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor _lowerCamelCase =logging.get_logger(__name__) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : str ,*snake_case : Optional[int] ,**snake_case : List[str] ): warnings.warn( 'The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PoolFormerImageProcessor instead.' ,snake_case ,) super().__init__(*snake_case ,**snake_case )
334
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): 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 =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): 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 _lowerCAmelCase ( self : Optional[int] ): return SqueezeBertConfig( embedding_size=self.hidden_size ,vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,attention_probs_dropout_prob=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,q_groups=self.q_groups ,k_groups=self.k_groups ,v_groups=self.v_groups ,post_attention_groups=self.post_attention_groups ,intermediate_groups=self.intermediate_groups ,output_groups=self.output_groups ,) def _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=snake_case ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) 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( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, 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)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
1
class a_ : """simple docstring""" def __init__( self : Dict ,snake_case : int ): SCREAMING_SNAKE_CASE =n SCREAMING_SNAKE_CASE =[None] * self.n SCREAMING_SNAKE_CASE =0 # index of the first element SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =0 def __len__( self : Optional[int] ): return self.size def _lowerCAmelCase ( self : Union[str, Any] ): return self.size == 0 def _lowerCAmelCase ( self : List[Any] ): return False if self.is_empty() else self.array[self.front] def _lowerCAmelCase ( self : str ,snake_case : Union[str, Any] ): if self.size >= self.n: raise Exception('QUEUE IS FULL' ) SCREAMING_SNAKE_CASE =data SCREAMING_SNAKE_CASE =(self.rear + 1) % self.n self.size += 1 return self def _lowerCAmelCase ( self : List[str] ): if self.size == 0: raise Exception('UNDERFLOW' ) SCREAMING_SNAKE_CASE =self.array[self.front] SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =(self.front + 1) % self.n self.size -= 1 return temp
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[] for data in source_data: for i, el in enumerate(lowerCAmelCase_ ): if len(lowerCAmelCase_ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(lowerCAmelCase_ ) ) return data_lists def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[] for dlist, weight in zip(lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =min(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =max(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =[] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE =F'Invalid weight of {weight:f} provided' raise ValueError(lowerCAmelCase_ ) score_lists.append(lowerCAmelCase_ ) return score_lists def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =[0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =final_scores[j] + ele return final_scores def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_data(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =calculate_each_score(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =generate_final_scores(lowerCAmelCase_ ) # append scores to source data for i, ele in enumerate(lowerCAmelCase_ ): source_data[i].append(lowerCAmelCase_ ) return source_data
334
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
1
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowerCamelCase =logging.getLogger(__name__) @dataclass class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = field( default=0.0 , metadata={'help': 'The label smoothing epsilon to apply (if not zero).'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Whether to SortishSamler or not.'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'whether to use adafactor'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Encoder layer dropout probability. Goes into model.config.'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Decoder layer dropout probability. Goes into model.config.'} ) __UpperCAmelCase = field(default=lowerCamelCase_ , metadata={'help': 'Dropout probability. Goes into model.config.'} ) __UpperCAmelCase = field( default=lowerCamelCase_ , metadata={'help': 'Attention dropout probability. Goes into model.config.'} ) __UpperCAmelCase = field( default='linear' , metadata={'help': F'''Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'''} , )
334
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
1
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class a_ ( unittest.TestCase ): """simple docstring""" @property def _lowerCAmelCase ( self : Optional[int] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE =UNetaDModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=3 ,out_channels=3 ,down_block_types=('DownBlock2D', 'AttnDownBlock2D') ,up_block_types=('AttnUpBlock2D', 'UpBlock2D') ,) return model def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.dummy_uncond_unet SCREAMING_SNAKE_CASE =ScoreSdeVeScheduler() SCREAMING_SNAKE_CASE =ScoreSdeVePipeline(unet=snake_case ,scheduler=snake_case ) sde_ve.to(snake_case ) sde_ve.set_progress_bar_config(disable=snake_case ) SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE =sde_ve(num_inference_steps=2 ,output_type='numpy' ,generator=snake_case ).images SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE =sde_ve(num_inference_steps=2 ,output_type='numpy' ,generator=snake_case ,return_dict=snake_case )[ 0 ] SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE =np.array([0.0, 1.0, 0.0, 0.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 a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE ='google/ncsnpp-church-256' SCREAMING_SNAKE_CASE =UNetaDModel.from_pretrained(snake_case ) SCREAMING_SNAKE_CASE =ScoreSdeVeScheduler.from_pretrained(snake_case ) SCREAMING_SNAKE_CASE =ScoreSdeVePipeline(unet=snake_case ,scheduler=snake_case ) sde_ve.to(snake_case ) sde_ve.set_progress_bar_config(disable=snake_case ) SCREAMING_SNAKE_CASE =torch.manual_seed(0 ) SCREAMING_SNAKE_CASE =sde_ve(num_inference_steps=10 ,output_type='numpy' ,generator=snake_case ).images SCREAMING_SNAKE_CASE =image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) SCREAMING_SNAKE_CASE =np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
334
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size 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 =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration _lowerCamelCase =pytest.mark.integration _lowerCamelCase ={"comet"} _lowerCamelCase =importlib.util.find_spec("fairseq") is not None _lowerCamelCase ={"code_eval"} _lowerCamelCase =os.name == "nt" _lowerCamelCase ={"bertscore", "frugalscore", "perplexity"} _lowerCamelCase =importlib.util.find_spec("transformers") is not None def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" @wraps(lowerCAmelCase_ ) def wrapper(self, lowerCAmelCase_ ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self, lowerCAmelCase_ ) return wrapper def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" @wraps(lowerCAmelCase_ ) def wrapper(self, lowerCAmelCase_ ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self, lowerCAmelCase_ ) return wrapper def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" @wraps(lowerCAmelCase_ ) def wrapper(self, lowerCAmelCase_ ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self, lowerCAmelCase_ ) return wrapper def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =[metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) @local class a_ ( parameterized.TestCase ): """simple docstring""" __UpperCAmelCase = {} __UpperCAmelCase = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning' ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE ='[...]' SCREAMING_SNAKE_CASE =importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' ,snake_case ) ).module_path ) SCREAMING_SNAKE_CASE =datasets.load.import_main_class(metric_module.__name__ ,dataset=snake_case ) # check parameters SCREAMING_SNAKE_CASE =inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(snake_case ,metric_module.__name__ ): with self.use_local_metrics(): try: SCREAMING_SNAKE_CASE =doctest.testmod(snake_case ,verbose=snake_case ,raise_on_error=snake_case ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed ,0 ) self.assertGreater(results.attempted ,1 ) @slow def _lowerCAmelCase ( self : Optional[int] ,snake_case : List[Any] ): SCREAMING_SNAKE_CASE ='[...]' SCREAMING_SNAKE_CASE =importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' ,snake_case ) ).module_path ) # run doctest with self.use_local_metrics(): SCREAMING_SNAKE_CASE =doctest.testmod(snake_case ,verbose=snake_case ,raise_on_error=snake_case ) self.assertEqual(results.failed ,0 ) self.assertGreater(results.attempted ,1 ) @contextmanager def _lowerCAmelCase ( self : List[str] ,snake_case : int ,snake_case : Optional[int] ): if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](snake_case ): yield else: yield @contextmanager def _lowerCAmelCase ( self : List[Any] ): def load_local_metric(snake_case : int ,*snake_case : Union[str, Any] ,**snake_case : List[str] ): return load_metric(os.path.join('metrics' ,snake_case ) ,*snake_case ,**snake_case ) with patch('datasets.load_metric' ) as mock_load_metric: SCREAMING_SNAKE_CASE =load_local_metric yield @classmethod def _lowerCAmelCase ( cls : Tuple ,snake_case : str ): def wrapper(snake_case : List[Any] ): SCREAMING_SNAKE_CASE =contextmanager(snake_case ) SCREAMING_SNAKE_CASE =patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv', '', '' ) # handle pytest cli flags class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ): assert len(input_dict['input_ids'] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: SCREAMING_SNAKE_CASE =MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" import torch def bert_cos_score_idf(lowerCAmelCase_, lowerCAmelCase_, *lowerCAmelCase_, **lowerCAmelCase_ ): return torch.tensor([[1.0, 1.0, 1.0]] * len(lowerCAmelCase_ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: SCREAMING_SNAKE_CASE =bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" def load_from_checkpoint(lowerCAmelCase_ ): class a_ : """simple docstring""" def _lowerCAmelCase ( self : str ,snake_case : Any ,*snake_case : List[Any] ,**snake_case : List[Any] ): assert len(snake_case ) == 2 SCREAMING_SNAKE_CASE =[0.19, 0.92] return scores, sum(snake_case ) / len(snake_case ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: SCREAMING_SNAKE_CASE =None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: SCREAMING_SNAKE_CASE =load_from_checkpoint yield def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =load_metric(os.path.join('metrics', 'seqeval' ) ) SCREAMING_SNAKE_CASE ='ERROR' SCREAMING_SNAKE_CASE =F'Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}' with pytest.raises(lowerCAmelCase_, match=re.escape(lowerCAmelCase_ ) ): metric.compute(predictions=[], references=[], scheme=lowerCAmelCase_ )
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _lowerCamelCase ={ "configuration_vision_text_dual_encoder": ["VisionTextDualEncoderConfig"], "processing_vision_text_dual_encoder": ["VisionTextDualEncoderProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["VisionTextDualEncoderModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["FlaxVisionTextDualEncoderModel"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["TFVisionTextDualEncoderModel"] if TYPE_CHECKING: from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure)
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
import re import string import numpy as np import datasets _lowerCamelCase ="\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n" _lowerCamelCase ="\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results[\"exact_match\"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"the cat\", \"theater\", \"YELLING\", \"agent007\"]\n >>> preds = [\"cat?\", \"theater\", \"yelling\", \"agent\"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=[\"the \", \"yell\", \"YELL\"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results[\"exact_match\"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric(\"exact_match\")\n >>> refs = [\"The cat sat on the mat.\", \"Theaters are great.\", \"It's like comparing oranges and apples.\"]\n >>> preds = [\"The cat sat on the mat?\", \"Theaters are great.\", \"It's like comparing apples and oranges.\"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results[\"exact_match\"], 1))\n 33.3\n\n" _lowerCamelCase ="\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : int ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,reference_urls=[] ,) def _lowerCAmelCase ( self : str ,snake_case : List[str] ,snake_case : List[str] ,snake_case : List[Any]=None ,snake_case : List[Any]=False ,snake_case : int=False ,snake_case : Optional[int]=False ,): if regexes_to_ignore is not None: for s in regexes_to_ignore: SCREAMING_SNAKE_CASE =np.array([re.sub(snake_case ,'' ,snake_case ) for x in predictions] ) SCREAMING_SNAKE_CASE =np.array([re.sub(snake_case ,'' ,snake_case ) for x in references] ) else: SCREAMING_SNAKE_CASE =np.asarray(snake_case ) SCREAMING_SNAKE_CASE =np.asarray(snake_case ) if ignore_case: SCREAMING_SNAKE_CASE =np.char.lower(snake_case ) SCREAMING_SNAKE_CASE =np.char.lower(snake_case ) if ignore_punctuation: SCREAMING_SNAKE_CASE =string.punctuation.maketrans('' ,'' ,string.punctuation ) SCREAMING_SNAKE_CASE =np.char.translate(snake_case ,table=snake_case ) SCREAMING_SNAKE_CASE =np.char.translate(snake_case ,table=snake_case ) if ignore_numbers: SCREAMING_SNAKE_CASE =string.digits.maketrans('' ,'' ,string.digits ) SCREAMING_SNAKE_CASE =np.char.translate(snake_case ,table=snake_case ) SCREAMING_SNAKE_CASE =np.char.translate(snake_case ,table=snake_case ) SCREAMING_SNAKE_CASE =predictions == references return {"exact_match": np.mean(snake_case ) * 100}
334
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 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 =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_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.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , 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 a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : 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(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : 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(snake_case ) 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] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
1
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow 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.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class a_ : """simple docstring""" __UpperCAmelCase = XGLMConfig __UpperCAmelCase = {} __UpperCAmelCase = 'gelu' def __init__( self : Any ,snake_case : Any ,snake_case : Union[str, Any]=14 ,snake_case : Dict=7 ,snake_case : str=True ,snake_case : Optional[Any]=True ,snake_case : List[Any]=True ,snake_case : List[str]=99 ,snake_case : List[Any]=32 ,snake_case : Union[str, Any]=2 ,snake_case : Dict=4 ,snake_case : str=37 ,snake_case : Tuple="gelu" ,snake_case : Union[str, Any]=0.1 ,snake_case : int=0.1 ,snake_case : int=512 ,snake_case : List[str]=0.02 ,): 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_labels SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_attention_heads SCREAMING_SNAKE_CASE =ffn_dim SCREAMING_SNAKE_CASE =activation_function SCREAMING_SNAKE_CASE =activation_dropout SCREAMING_SNAKE_CASE =attention_dropout SCREAMING_SNAKE_CASE =max_position_embeddings SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =2 SCREAMING_SNAKE_CASE =1 def _lowerCAmelCase ( self : Any ): return XGLMConfig.from_pretrained('facebook/xglm-564M' ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) ,clip_value_min=0 ,clip_value_max=3 ) SCREAMING_SNAKE_CASE =None if self.use_input_mask: SCREAMING_SNAKE_CASE =random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE =self.get_config() SCREAMING_SNAKE_CASE =floats_tensor([self.num_hidden_layers, self.num_attention_heads] ,2 ) return ( config, input_ids, input_mask, head_mask, ) def _lowerCAmelCase ( self : Optional[Any] ): return XGLMConfig( vocab_size=self.vocab_size ,d_model=self.hidden_size ,num_layers=self.num_hidden_layers ,attention_heads=self.num_attention_heads ,ffn_dim=self.ffn_dim ,activation_function=self.activation_function ,activation_dropout=self.activation_dropout ,attention_dropout=self.attention_dropout ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,use_cache=snake_case ,bos_token_id=self.bos_token_id ,eos_token_id=self.eos_token_id ,pad_token_id=self.pad_token_id ,return_dict=snake_case ,) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ( SCREAMING_SNAKE_CASE ) , ) =config_and_inputs SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () __UpperCAmelCase = (TFXGLMForCausalLM,) if is_tf_available() else () __UpperCAmelCase = ( {'feature-extraction': TFXGLMModel, 'text-generation': TFXGLMForCausalLM} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =TFXGLMModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,n_embd=37 ) def _lowerCAmelCase ( self : Any ): self.config_tester.run_common_tests() @slow def _lowerCAmelCase ( self : List[str] ): for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =TFXGLMModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' ) def _lowerCAmelCase ( self : Union[str, Any] ): super().test_resize_token_embeddings() @require_tf class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int=True ): SCREAMING_SNAKE_CASE =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) SCREAMING_SNAKE_CASE =tf.convert_to_tensor([[2, 268, 9865]] ,dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off SCREAMING_SNAKE_CASE =[2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581] # fmt: on SCREAMING_SNAKE_CASE =model.generate(snake_case ,do_sample=snake_case ,num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() ,snake_case ) @slow def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) SCREAMING_SNAKE_CASE =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE =tokenizer('Today is a nice day and' ,return_tensors='tf' ) SCREAMING_SNAKE_CASE =tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0' ): SCREAMING_SNAKE_CASE =model.generate(snake_case ,do_sample=snake_case ,seed=[7, 0] ) SCREAMING_SNAKE_CASE =tokenizer.decode(output_ids[0] ,skip_special_tokens=snake_case ) SCREAMING_SNAKE_CASE =( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(snake_case ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) SCREAMING_SNAKE_CASE =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) SCREAMING_SNAKE_CASE ='left' # use different length sentences to test batching SCREAMING_SNAKE_CASE =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] SCREAMING_SNAKE_CASE =tokenizer(snake_case ,return_tensors='tf' ,padding=snake_case ) SCREAMING_SNAKE_CASE =inputs['input_ids'] SCREAMING_SNAKE_CASE =model.generate(input_ids=snake_case ,attention_mask=inputs['attention_mask'] ,max_new_tokens=12 ) SCREAMING_SNAKE_CASE =tokenizer(sentences[0] ,return_tensors='tf' ).input_ids SCREAMING_SNAKE_CASE =model.generate(input_ids=snake_case ,max_new_tokens=12 ) SCREAMING_SNAKE_CASE =tokenizer(sentences[1] ,return_tensors='tf' ).input_ids SCREAMING_SNAKE_CASE =model.generate(input_ids=snake_case ,max_new_tokens=12 ) SCREAMING_SNAKE_CASE =tokenizer.batch_decode(snake_case ,skip_special_tokens=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.decode(output_non_padded[0] ,skip_special_tokens=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.decode(output_padded[0] ,skip_special_tokens=snake_case ) SCREAMING_SNAKE_CASE =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(snake_case ,snake_case ) self.assertListEqual(snake_case ,[non_padded_sentence, padded_sentence] )
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): 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 =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): 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 _lowerCAmelCase ( self : Optional[int] ): return SqueezeBertConfig( embedding_size=self.hidden_size ,vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,attention_probs_dropout_prob=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,q_groups=self.q_groups ,k_groups=self.k_groups ,v_groups=self.v_groups ,post_attention_groups=self.post_attention_groups ,intermediate_groups=self.intermediate_groups ,output_groups=self.output_groups ,) def _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=snake_case ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) 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( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, 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)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
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 # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( 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 _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( 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 snake_case__ ( ): """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()
334
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase ={ "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
1
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
1
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow 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 numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class a_ : """simple docstring""" def __init__( self : Optional[Any] ,snake_case : Any ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =13 SCREAMING_SNAKE_CASE =7 SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =99 SCREAMING_SNAKE_CASE =32 SCREAMING_SNAKE_CASE =2 SCREAMING_SNAKE_CASE =4 SCREAMING_SNAKE_CASE =37 SCREAMING_SNAKE_CASE ='gelu' SCREAMING_SNAKE_CASE =0.1 SCREAMING_SNAKE_CASE =0.1 SCREAMING_SNAKE_CASE =512 SCREAMING_SNAKE_CASE =16 SCREAMING_SNAKE_CASE =2 SCREAMING_SNAKE_CASE =0.02 SCREAMING_SNAKE_CASE =3 SCREAMING_SNAKE_CASE =4 SCREAMING_SNAKE_CASE =None def _lowerCAmelCase ( self : str ): 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 =EsmConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,pad_token_id=1 ,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 config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowerCAmelCase ( self : Union[str, Any] ): ( ( 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, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _lowerCAmelCase ( self : Tuple ,snake_case : Dict ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =TFEsmModel(config=snake_case ) SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} SCREAMING_SNAKE_CASE =model(snake_case ) SCREAMING_SNAKE_CASE =[input_ids, input_mask] SCREAMING_SNAKE_CASE =model(snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Any ,snake_case : int ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,): SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =TFEsmModel(config=snake_case ) SCREAMING_SNAKE_CASE ={ 'input_ids': input_ids, 'attention_mask': input_mask, 'encoder_hidden_states': encoder_hidden_states, 'encoder_attention_mask': encoder_attention_mask, } SCREAMING_SNAKE_CASE =model(snake_case ) SCREAMING_SNAKE_CASE =[input_ids, input_mask] SCREAMING_SNAKE_CASE =model(snake_case ,encoder_hidden_states=snake_case ) # Also check the case where encoder outputs are not passed SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : str ,snake_case : int ,snake_case : List[str] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Dict ): SCREAMING_SNAKE_CASE =TFEsmForMaskedLM(config=snake_case ) SCREAMING_SNAKE_CASE =model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : int ,snake_case : Any ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Optional[Any] ,snake_case : str ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =TFEsmForTokenClassification(config=snake_case ) SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : 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 ) , ) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': TFEsmModel, 'fill-mask': TFEsmForMaskedLM, 'text-classification': TFEsmForSequenceClassification, 'token-classification': TFEsmForTokenClassification, 'zero-shot': TFEsmForSequenceClassification, } if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =TFEsmModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : Tuple ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =TFEsmModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @unittest.skip('Protein models do not support embedding resizing.' ) def _lowerCAmelCase ( self : int ): pass @unittest.skip('Protein models do not support embedding resizing.' ) def _lowerCAmelCase ( self : Dict ): pass def _lowerCAmelCase ( self : Union[str, 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(snake_case ) assert isinstance(model.get_input_embeddings() ,tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer SCREAMING_SNAKE_CASE =model.get_bias() assert isinstance(snake_case ,snake_case ) for k, v in name.items(): assert isinstance(snake_case ,tf.Variable ) else: SCREAMING_SNAKE_CASE =model.get_output_embeddings() assert x is None SCREAMING_SNAKE_CASE =model.get_bias() assert name is None @require_tf class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) SCREAMING_SNAKE_CASE =tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =[1, 6, 33] self.assertEqual(list(output.numpy().shape ) ,snake_case ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE =tf.constant( [ [ [8.921_518, -10.589_814, -6.4_671_307], [-6.3_967_156, -13.911_377, -1.1_211_915], [-7.781_247, -13.951_557, -3.740_592], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) SCREAMING_SNAKE_CASE =tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] # compare the actual values for a slice. SCREAMING_SNAKE_CASE =tf.constant( [ [ [0.14_443_092, 0.54_125_327, 0.3_247_739], [0.30_340_484, 0.00_526_676, 0.31_077_722], [0.32_278_043, -0.24_987_096, 0.3_414_628], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1e-4 ) )
334
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size 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 SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": 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(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) 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 =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
1
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets _lowerCamelCase ="\\n@inproceedings{lin-2004-rouge,\n title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",\n author = \"Lin, Chin-Yew\",\n booktitle = \"Text Summarization Branches Out\",\n month = jul,\n year = \"2004\",\n address = \"Barcelona, Spain\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W04-1013\",\n pages = \"74--81\",\n}\n" _lowerCamelCase ="\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n" _lowerCamelCase ="\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,\n `\"rougeL\"`: Longest common subsequence based scoring.\n `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric('rouge')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']\n >>> print(results[\"rouge1\"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results[\"rouge1\"].mid.fmeasure)\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] ,reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] ,) def _lowerCAmelCase ( self : str ,snake_case : Optional[Any] ,snake_case : Tuple ,snake_case : List[Any]=None ,snake_case : List[str]=True ,snake_case : Any=False ): if rouge_types is None: SCREAMING_SNAKE_CASE =['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] SCREAMING_SNAKE_CASE =rouge_scorer.RougeScorer(rouge_types=snake_case ,use_stemmer=snake_case ) if use_aggregator: SCREAMING_SNAKE_CASE =scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE =[] for ref, pred in zip(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =scorer.score(snake_case ,snake_case ) if use_aggregator: aggregator.add_scores(snake_case ) else: scores.append(snake_case ) if use_aggregator: SCREAMING_SNAKE_CASE =aggregator.aggregate() else: SCREAMING_SNAKE_CASE ={} for key in scores[0]: SCREAMING_SNAKE_CASE =[score[key] for score in scores] return result
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "tensor(bool)": np.bool_, "tensor(int8)": np.inta, "tensor(uint8)": np.uinta, "tensor(int16)": np.intaa, "tensor(uint16)": np.uintaa, "tensor(int32)": np.intaa, "tensor(uint32)": np.uintaa, "tensor(int64)": np.intaa, "tensor(uint64)": np.uintaa, "tensor(float16)": np.floataa, "tensor(float)": np.floataa, "tensor(double)": np.floataa, } class a_ : """simple docstring""" def __init__( self : Optional[Any] ,snake_case : int=None ,**snake_case : Dict ): logger.info('`diffusers.OnnxRuntimeModel` is experimental and might change in the future.' ) SCREAMING_SNAKE_CASE =model SCREAMING_SNAKE_CASE =kwargs.get('model_save_dir' ,snake_case ) SCREAMING_SNAKE_CASE =kwargs.get('latest_model_name' ,snake_case ) def __call__( self : Tuple ,**snake_case : str ): SCREAMING_SNAKE_CASE ={k: np.array(snake_case ) for k, v in kwargs.items()} return self.model.run(snake_case ,snake_case ) @staticmethod def _lowerCAmelCase ( snake_case : Union[str, Path] ,snake_case : Any=None ,snake_case : str=None ): if provider is None: logger.info('No onnxruntime provider specified, using CPUExecutionProvider' ) SCREAMING_SNAKE_CASE ='CPUExecutionProvider' return ort.InferenceSession(snake_case ,providers=[provider] ,sess_options=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[str, Path] ,snake_case : Optional[str] = None ,**snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =file_name if file_name is not None else ONNX_WEIGHTS_NAME SCREAMING_SNAKE_CASE =self.model_save_dir.joinpath(self.latest_model_name ) SCREAMING_SNAKE_CASE =Path(snake_case ).joinpath(snake_case ) try: shutil.copyfile(snake_case ,snake_case ) except shutil.SameFileError: pass # copy external weights (for models >2GB) SCREAMING_SNAKE_CASE =self.model_save_dir.joinpath(snake_case ) if src_path.exists(): SCREAMING_SNAKE_CASE =Path(snake_case ).joinpath(snake_case ) try: shutil.copyfile(snake_case ,snake_case ) except shutil.SameFileError: pass def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Union[str, Any] ,): if os.path.isfile(snake_case ): logger.error(f'Provided path ({save_directory}) should be a directory, not a file' ) return os.makedirs(snake_case ,exist_ok=snake_case ) # saving model weights/files self._save_pretrained(snake_case ,**snake_case ) @classmethod def _lowerCAmelCase ( cls : Optional[Any] ,snake_case : Union[str, Path] ,snake_case : Optional[Union[bool, str, None]] = None ,snake_case : Optional[Union[str, None]] = None ,snake_case : bool = False ,snake_case : Optional[str] = None ,snake_case : Optional[str] = None ,snake_case : Optional[str] = None ,snake_case : Optional["ort.SessionOptions"] = None ,**snake_case : Optional[Any] ,): SCREAMING_SNAKE_CASE =file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(snake_case ): SCREAMING_SNAKE_CASE =OnnxRuntimeModel.load_model( os.path.join(snake_case ,snake_case ) ,provider=snake_case ,sess_options=snake_case ) SCREAMING_SNAKE_CASE =Path(snake_case ) # load model from hub else: # download model SCREAMING_SNAKE_CASE =hf_hub_download( repo_id=snake_case ,filename=snake_case ,use_auth_token=snake_case ,revision=snake_case ,cache_dir=snake_case ,force_download=snake_case ,) SCREAMING_SNAKE_CASE =Path(snake_case ).parent SCREAMING_SNAKE_CASE =Path(snake_case ).name SCREAMING_SNAKE_CASE =OnnxRuntimeModel.load_model(snake_case ,provider=snake_case ,sess_options=snake_case ) return cls(model=snake_case ,**snake_case ) @classmethod def _lowerCAmelCase ( cls : Optional[Any] ,snake_case : Union[str, Path] ,snake_case : bool = True ,snake_case : Optional[str] = None ,snake_case : Optional[str] = None ,**snake_case : Optional[Any] ,): SCREAMING_SNAKE_CASE =None if len(str(snake_case ).split('@' ) ) == 2: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =model_id.split('@' ) return cls._from_pretrained( model_id=snake_case ,revision=snake_case ,cache_dir=snake_case ,force_download=snake_case ,use_auth_token=snake_case ,**snake_case ,)
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) 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 =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
1
from typing import List, Optional, Union import numpy as np import PIL import torch from PIL import Image from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) _lowerCamelCase =logging.get_logger(__name__) # pylint: disable=invalid-name _lowerCamelCase ="\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"A red cartoon frog, 4k\"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n ... )\n >>> pipe.to(\"cuda\")\n\n >>> init_image = load_image(\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n ... \"/kandinsky/frog.png\"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save(\"red_frog.png\")\n ```\n" def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=8 ): """simple docstring""" SCREAMING_SNAKE_CASE =height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE =width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=512, lowerCAmelCase_=512 ): """simple docstring""" SCREAMING_SNAKE_CASE =pil_image.resize((w, h), resample=Image.BICUBIC, reducing_gap=1 ) SCREAMING_SNAKE_CASE =np.array(pil_image.convert('RGB' ) ) SCREAMING_SNAKE_CASE =arr.astype(np.floataa ) / 127.5 - 1 SCREAMING_SNAKE_CASE =np.transpose(lowerCAmelCase_, [2, 0, 1] ) SCREAMING_SNAKE_CASE =torch.from_numpy(lowerCAmelCase_ ).unsqueeze(0 ) return image class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Optional[int] ,snake_case : UNetaDConditionModel ,snake_case : DDPMScheduler ,snake_case : VQModel ,): super().__init__() self.register_modules( unet=snake_case ,scheduler=snake_case ,movq=snake_case ,) SCREAMING_SNAKE_CASE =2 ** (len(self.movq.config.block_out_channels ) - 1) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ,snake_case : str ,snake_case : Any ): # get the original timestep using init_timestep SCREAMING_SNAKE_CASE =min(int(num_inference_steps * strength ) ,snake_case ) SCREAMING_SNAKE_CASE =max(num_inference_steps - init_timestep ,0 ) SCREAMING_SNAKE_CASE =self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def _lowerCAmelCase ( self : Optional[int] ,snake_case : Any ,snake_case : Union[str, Any] ,snake_case : Tuple ,snake_case : Dict ,snake_case : Optional[int] ,snake_case : Optional[int] ,snake_case : List[Any]=None ): if not isinstance(snake_case ,(torch.Tensor, PIL.Image.Image, list) ): raise ValueError( f'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(snake_case )}' ) SCREAMING_SNAKE_CASE =image.to(device=snake_case ,dtype=snake_case ) SCREAMING_SNAKE_CASE =batch_size * num_images_per_prompt if image.shape[1] == 4: SCREAMING_SNAKE_CASE =image else: if isinstance(snake_case ,snake_case ) and len(snake_case ) != batch_size: raise ValueError( f'You have passed a list of generators of length {len(snake_case )}, but requested an effective batch' f' size of {batch_size}. Make sure the batch size matches the length of the generators.' ) elif isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =[ self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(snake_case ) ] SCREAMING_SNAKE_CASE =torch.cat(snake_case ,dim=0 ) else: SCREAMING_SNAKE_CASE =self.movq.encode(snake_case ).latent_dist.sample(snake_case ) SCREAMING_SNAKE_CASE =self.movq.config.scaling_factor * init_latents SCREAMING_SNAKE_CASE =torch.cat([init_latents] ,dim=0 ) SCREAMING_SNAKE_CASE =init_latents.shape SCREAMING_SNAKE_CASE =randn_tensor(snake_case ,generator=snake_case ,device=snake_case ,dtype=snake_case ) # get latents SCREAMING_SNAKE_CASE =self.scheduler.add_noise(snake_case ,snake_case ,snake_case ) SCREAMING_SNAKE_CASE =init_latents return latents def _lowerCAmelCase ( self : Any ,snake_case : Optional[Any]=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) SCREAMING_SNAKE_CASE =torch.device(f'cuda:{gpu_id}' ) SCREAMING_SNAKE_CASE =[ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(snake_case ,snake_case ) def _lowerCAmelCase ( self : int ,snake_case : Any=0 ): if is_accelerate_available() and is_accelerate_version('>=' ,'0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) SCREAMING_SNAKE_CASE =torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('cpu' ,silence_dtype_warnings=snake_case ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE =None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cpu_offload_with_hook(snake_case ,snake_case ,prev_module_hook=snake_case ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE =hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowerCAmelCase ( self : List[Any] ): if not hasattr(self.unet ,'_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(snake_case ,'_hf_hook' ) and hasattr(module._hf_hook ,'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(snake_case ) def __call__( self : Any ,snake_case : Union[torch.FloatTensor, List[torch.FloatTensor]] ,snake_case : Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]] ,snake_case : Union[torch.FloatTensor, List[torch.FloatTensor]] ,snake_case : int = 512 ,snake_case : int = 512 ,snake_case : int = 100 ,snake_case : float = 4.0 ,snake_case : float = 0.3 ,snake_case : int = 1 ,snake_case : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,snake_case : Optional[str] = "pil" ,snake_case : bool = True ,): SCREAMING_SNAKE_CASE =self._execution_device SCREAMING_SNAKE_CASE =guidance_scale > 1.0 if isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =torch.cat(snake_case ,dim=0 ) SCREAMING_SNAKE_CASE =image_embeds.shape[0] if isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =torch.cat(snake_case ,dim=0 ) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE =image_embeds.repeat_interleave(snake_case ,dim=0 ) SCREAMING_SNAKE_CASE =negative_image_embeds.repeat_interleave(snake_case ,dim=0 ) SCREAMING_SNAKE_CASE =torch.cat([negative_image_embeds, image_embeds] ,dim=0 ).to(dtype=self.unet.dtype ,device=snake_case ) if not isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =[image] if not all(isinstance(snake_case ,(PIL.Image.Image, torch.Tensor) ) for i in image ): raise ValueError( f'Input is in incorrect format: {[type(snake_case ) for i in image]}. Currently, we only support PIL image and pytorch tensor' ) SCREAMING_SNAKE_CASE =torch.cat([prepare_image(snake_case ,snake_case ,snake_case ) for i in image] ,dim=0 ) SCREAMING_SNAKE_CASE =image.to(dtype=image_embeds.dtype ,device=snake_case ) SCREAMING_SNAKE_CASE =self.movq.encode(snake_case )['latents'] SCREAMING_SNAKE_CASE =latents.repeat_interleave(snake_case ,dim=0 ) self.scheduler.set_timesteps(snake_case ,device=snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.get_timesteps(snake_case ,snake_case ,snake_case ) SCREAMING_SNAKE_CASE =timesteps[:1].repeat(batch_size * num_images_per_prompt ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =downscale_height_and_width(snake_case ,snake_case ,self.movq_scale_factor ) SCREAMING_SNAKE_CASE =self.prepare_latents( snake_case ,snake_case ,snake_case ,snake_case ,image_embeds.dtype ,snake_case ,snake_case ) for i, t in enumerate(self.progress_bar(snake_case ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE =torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE ={'image_embeds': image_embeds} SCREAMING_SNAKE_CASE =self.unet( sample=snake_case ,timestep=snake_case ,encoder_hidden_states=snake_case ,added_cond_kwargs=snake_case ,return_dict=snake_case ,)[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =noise_pred.split(latents.shape[1] ,dim=1 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE =noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE =torch.cat([noise_pred, variance_pred_text] ,dim=1 ) if not ( hasattr(self.scheduler.config ,'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =noise_pred.split(latents.shape[1] ,dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE =self.scheduler.step( snake_case ,snake_case ,snake_case ,generator=snake_case ,)[0] # post-processing SCREAMING_SNAKE_CASE =self.movq.decode(snake_case ,force_not_quantize=snake_case )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE =image * 0.5 + 0.5 SCREAMING_SNAKE_CASE =image.clamp(0 ,1 ) SCREAMING_SNAKE_CASE =image.cpu().permute(0 ,2 ,3 ,1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE =self.numpy_to_pil(snake_case ) if not return_dict: return (image,) return ImagePipelineOutput(images=snake_case )
334
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
1
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "dict" __UpperCAmelCase = None __UpperCAmelCase = field(default='Translation' , init=lowerCamelCase_ , repr=lowerCamelCase_ ) def __call__( self : str ): return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def _lowerCAmelCase ( self : Tuple ): from .features import Value return {k: Value('string' ) for k in sorted(self.languages )} @dataclass class a_ : """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None __UpperCAmelCase = None # Automatically constructed __UpperCAmelCase = "dict" __UpperCAmelCase = None __UpperCAmelCase = field(default='TranslationVariableLanguages' , init=lowerCamelCase_ , repr=lowerCamelCase_ ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =sorted(set(self.languages ) ) if self.languages else None SCREAMING_SNAKE_CASE =len(self.languages ) if self.languages else None def __call__( self : Dict ): return pa.struct({'language': pa.list_(pa.string() ), 'translation': pa.list_(pa.string() )} ) def _lowerCAmelCase ( self : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =set(self.languages ) if self.languages and set(snake_case ) - lang_set: raise ValueError( f'Some languages in example ({", ".join(sorted(set(snake_case ) - lang_set ) )}) are not in valid set ({", ".join(snake_case )}).' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE =[] for lang, text in translation_dict.items(): if isinstance(snake_case ,snake_case ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =zip(*sorted(snake_case ) ) return {"language": languages, "translation": translations} def _lowerCAmelCase ( self : Optional[Any] ): from .features import Sequence, Value return { "language": Sequence(Value('string' ) ), "translation": Sequence(Value('string' ) ), }
334
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: writer.write({'col_1': 'foo', 'col_2': 1}, key=1 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=2 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =value @pytest.mark.parametrize('optimized_int_type, expected_dtype', [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype', [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ], ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
1
import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" @parameterized.expand([(None,), ('foo.json',)] ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ): SCREAMING_SNAKE_CASE =GenerationConfig( do_sample=snake_case ,temperature=0.7 ,length_penalty=1.0 ,bad_words_ids=[[1, 2, 3], [4, 5]] ,) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(snake_case ,config_name=snake_case ) SCREAMING_SNAKE_CASE =GenerationConfig.from_pretrained(snake_case ,config_name=snake_case ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample ,snake_case ) self.assertEqual(loaded_config.temperature ,0.7 ) self.assertEqual(loaded_config.length_penalty ,1.0 ) self.assertEqual(loaded_config.bad_words_ids ,[[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k ,50 ) self.assertEqual(loaded_config.max_length ,20 ) self.assertEqual(loaded_config.max_time ,snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =AutoConfig.from_pretrained('gpt2' ) SCREAMING_SNAKE_CASE =GenerationConfig.from_model_config(snake_case ) SCREAMING_SNAKE_CASE =GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(snake_case ,snake_case ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id ,default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id ,model_config.eos_token_id ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =GenerationConfig() SCREAMING_SNAKE_CASE ={ 'max_new_tokens': 1024, 'foo': 'bar', } SCREAMING_SNAKE_CASE =copy.deepcopy(snake_case ) SCREAMING_SNAKE_CASE =generation_config.update(**snake_case ) # update_kwargs was not modified (no side effects) self.assertEqual(snake_case ,snake_case ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens ,1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(snake_case ,{'foo': 'bar'} ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =GenerationConfig() SCREAMING_SNAKE_CASE ='bar' with tempfile.TemporaryDirectory('test-generation-config' ) as tmp_dir: generation_config.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =GenerationConfig.from_pretrained(snake_case ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo ,'bar' ) SCREAMING_SNAKE_CASE =GenerationConfig.from_model_config(snake_case ) assert not hasattr(snake_case ,'foo' ) # no new kwargs should be initialized if from config def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =GenerationConfig() self.assertEqual(default_config.temperature ,1.0 ) self.assertEqual(default_config.do_sample ,snake_case ) self.assertEqual(default_config.num_beams ,1 ) SCREAMING_SNAKE_CASE =GenerationConfig( do_sample=snake_case ,temperature=0.7 ,length_penalty=1.0 ,bad_words_ids=[[1, 2, 3], [4, 5]] ,) self.assertEqual(config.temperature ,0.7 ) self.assertEqual(config.do_sample ,snake_case ) self.assertEqual(config.num_beams ,1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =GenerationConfig.from_pretrained(snake_case ,temperature=1.0 ) self.assertEqual(loaded_config.temperature ,1.0 ) self.assertEqual(loaded_config.do_sample ,snake_case ) self.assertEqual(loaded_config.num_beams ,1 ) # default value @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" @classmethod def _lowerCAmelCase ( cls : List[str] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Any ): try: delete_repo(token=cls._token ,repo_id='test-generation-config' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-generation-config-org' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =GenerationConfig( do_sample=snake_case ,temperature=0.7 ,length_penalty=1.0 ,) config.push_to_hub('test-generation-config' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =GenerationConfig.from_pretrained(f'{USER}/test-generation-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(snake_case ,getattr(snake_case ,snake_case ) ) # Reset repo delete_repo(token=self._token ,repo_id='test-generation-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( snake_case ,repo_id='test-generation-config' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =GenerationConfig.from_pretrained(f'{USER}/test-generation-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(snake_case ,getattr(snake_case ,snake_case ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =GenerationConfig( do_sample=snake_case ,temperature=0.7 ,length_penalty=1.0 ,) config.push_to_hub('valid_org/test-generation-config-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(snake_case ,getattr(snake_case ,snake_case ) ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-generation-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( snake_case ,repo_id='valid_org/test-generation-config-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =GenerationConfig.from_pretrained('valid_org/test-generation-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(snake_case ,getattr(snake_case ,snake_case ) )
334
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
1
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu _lowerCamelCase =get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: _lowerCamelCase =json.load(f) @require_torch class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ,snake_case : Dict ): return FSMTTokenizer.from_pretrained(snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : List[Any] ): SCREAMING_SNAKE_CASE =FSMTForConditionalGeneration.from_pretrained(snake_case ).to(snake_case ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def _lowerCAmelCase ( self : List[Any] ,snake_case : int ,snake_case : Tuple ): # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE =f'facebook/wmt19-{pair}' SCREAMING_SNAKE_CASE =self.get_tokenizer(snake_case ) SCREAMING_SNAKE_CASE =self.get_model(snake_case ) SCREAMING_SNAKE_CASE =bleu_data[pair]['src'] SCREAMING_SNAKE_CASE =bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE =tokenizer(snake_case ,return_tensors='pt' ,truncation=snake_case ,padding='longest' ).to(snake_case ) SCREAMING_SNAKE_CASE =model.generate( input_ids=batch.input_ids ,num_beams=8 ,) SCREAMING_SNAKE_CASE =tokenizer.batch_decode( snake_case ,skip_special_tokens=snake_case ,clean_up_tokenization_spaces=snake_case ) SCREAMING_SNAKE_CASE =calculate_bleu(snake_case ,snake_case ) print(snake_case ) self.assertGreaterEqual(scores['bleu'] ,snake_case )
334
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _lowerCamelCase ={} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["MLukeTokenizer"] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
import inspect import unittest from math import floor from transformers import CvtConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import CvtForImageClassification, CvtModel from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(snake_case ,'embed_dim' ) ) self.parent.assertTrue(hasattr(snake_case ,'num_heads' ) ) class a_ : """simple docstring""" def __init__( self : List[str] ,snake_case : List[Any] ,snake_case : Any=13 ,snake_case : Dict=64 ,snake_case : Optional[int]=3 ,snake_case : List[Any]=[16, 48, 96] ,snake_case : int=[1, 3, 6] ,snake_case : Union[str, Any]=[1, 2, 10] ,snake_case : Optional[Any]=[7, 3, 3] ,snake_case : Any=[4, 2, 2] ,snake_case : List[Any]=[2, 1, 1] ,snake_case : Optional[int]=[2, 2, 2] ,snake_case : Optional[int]=[False, False, True] ,snake_case : List[str]=[0.0, 0.0, 0.0] ,snake_case : List[Any]=0.02 ,snake_case : Optional[int]=1e-12 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Optional[int]=2 ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =batch_size SCREAMING_SNAKE_CASE =image_size SCREAMING_SNAKE_CASE =patch_sizes SCREAMING_SNAKE_CASE =patch_stride SCREAMING_SNAKE_CASE =patch_padding SCREAMING_SNAKE_CASE =is_training SCREAMING_SNAKE_CASE =use_labels SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =embed_dim SCREAMING_SNAKE_CASE =num_heads SCREAMING_SNAKE_CASE =stride_kv SCREAMING_SNAKE_CASE =depth SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =attention_drop_rate SCREAMING_SNAKE_CASE =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps def _lowerCAmelCase ( self : Any ): 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.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels def _lowerCAmelCase ( self : Tuple ): return CvtConfig( image_size=self.image_size ,num_labels=self.num_labels ,num_channels=self.num_channels ,embed_dim=self.embed_dim ,num_heads=self.num_heads ,patch_sizes=self.patch_sizes ,patch_padding=self.patch_padding ,patch_stride=self.patch_stride ,stride_kv=self.stride_kv ,depth=self.depth ,cls_token=self.cls_token ,attention_drop_rate=self.attention_drop_rate ,initializer_range=self.initializer_range ,) def _lowerCAmelCase ( self : List[str] ,snake_case : int ,snake_case : Union[str, Any] ,snake_case : Any ): SCREAMING_SNAKE_CASE =CvtModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) SCREAMING_SNAKE_CASE =(self.image_size, self.image_size) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =image_size[0], image_size[1] for i in range(len(self.depth ) ): SCREAMING_SNAKE_CASE =floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) SCREAMING_SNAKE_CASE =floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.embed_dim[-1], height, width) ) def _lowerCAmelCase ( self : Dict ,snake_case : Any ,snake_case : int ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =CvtForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Tuple ): 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 a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = (CvtModel, CvtForImageClassification) if is_torch_available() else () __UpperCAmelCase = ( {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =CvtModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : Optional[Any] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _lowerCAmelCase ( self : Union[str, Any] ): return @unittest.skip(reason='Cvt does not output attentions' ) def _lowerCAmelCase ( self : Tuple ): pass @unittest.skip(reason='Cvt does not use inputs_embeds' ) def _lowerCAmelCase ( self : int ): pass @unittest.skip(reason='Cvt does not support input and output embeddings' ) def _lowerCAmelCase ( self : List[str] ): pass def _lowerCAmelCase ( self : List[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(snake_case ) 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] ,snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Dict ): def check_hidden_states_output(snake_case : int ,snake_case : str ,snake_case : List[Any] ): SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**self._prepare_for_class(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =outputs.hidden_states SCREAMING_SNAKE_CASE =len(self.model_tester.depth ) self.assertEqual(len(snake_case ) ,snake_case ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) ,[ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] ,) 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 =True check_hidden_states_output(snake_case ,snake_case ,snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE =True check_hidden_states_output(snake_case ,snake_case ,snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _lowerCAmelCase ( self : Optional[Any] ): pass @slow def _lowerCAmelCase ( self : List[Any] ): for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =CvtModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([0.9_285, 0.9_015, -0.3_150] ).to(snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,snake_case ,atol=1e-4 ) )
334
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
1
from typing import TYPE_CHECKING from ..utils import _LazyModule _lowerCamelCase ={ "config": [ "EXTERNAL_DATA_FORMAT_SIZE_LIMIT", "OnnxConfig", "OnnxConfigWithPast", "OnnxSeq2SeqConfigWithPast", "PatchingSpec", ], "convert": ["export", "validate_model_outputs"], "features": ["FeaturesManager"], "utils": ["ParameterFormat", "compute_serialized_parameters_size"], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): 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 =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): 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 _lowerCAmelCase ( self : Optional[int] ): return SqueezeBertConfig( embedding_size=self.hidden_size ,vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,attention_probs_dropout_prob=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,q_groups=self.q_groups ,k_groups=self.k_groups ,v_groups=self.v_groups ,post_attention_groups=self.post_attention_groups ,intermediate_groups=self.intermediate_groups ,output_groups=self.output_groups ,) def _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=snake_case ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) 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( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, 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)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
1
import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor _lowerCamelCase =logging.get_logger(__name__) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Dict ,*snake_case : str ,**snake_case : int ): warnings.warn( 'The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use SegformerImageProcessor instead.' ,snake_case ,) super().__init__(*snake_case ,**snake_case )
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
import math def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if initial_intensity < 0: raise ValueError('The value of intensity cannot be negative' ) # handling of negative values of initial intensity if angle < 0 or angle > 360: raise ValueError('In Malus Law, the angle is in the range 0-360 degrees' ) # handling of values out of allowed range return initial_intensity * (math.cos(math.radians(lowerCAmelCase_ ) ) ** 2) if __name__ == "__main__": import doctest doctest.testmod(name="malus_law")
334
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
1
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class a_ : """simple docstring""" def __init__( self : List[str] ,snake_case : Any ,snake_case : Optional[Any]=13 ,snake_case : int=7 ,snake_case : Optional[Any]=True ,snake_case : List[Any]=True ,snake_case : Tuple=True ,snake_case : Union[str, Any]=True ,snake_case : Optional[int]=99 ,snake_case : Tuple=16 ,snake_case : Dict=36 ,snake_case : str=6 ,snake_case : Dict=6 ,snake_case : List[str]=6 ,snake_case : Union[str, Any]=37 ,snake_case : Tuple="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Any=0.1 ,snake_case : Optional[int]=512 ,snake_case : int=16 ,snake_case : Union[str, Any]=2 ,snake_case : str=0.02 ,snake_case : List[str]=3 ,snake_case : Optional[int]=4 ,snake_case : Dict=None ,): 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 =embedding_size SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =num_hidden_layers SCREAMING_SNAKE_CASE =num_hidden_groups 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 _lowerCAmelCase ( self : List[str] ): 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 _lowerCAmelCase ( self : Optional[int] ): return AlbertConfig( vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,type_vocab_size=self.type_vocab_size ,initializer_range=self.initializer_range ,num_hidden_groups=self.num_hidden_groups ,) def _lowerCAmelCase ( self : Dict ,snake_case : List[Any] ,snake_case : Tuple ,snake_case : Optional[int] ,snake_case : Any ,snake_case : List[str] ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =AlbertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ,token_type_ids=snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape ,(self.batch_size, self.hidden_size) ) def _lowerCAmelCase ( self : str ,snake_case : Optional[Any] ,snake_case : Any ,snake_case : int ,snake_case : Tuple ,snake_case : int ,snake_case : int ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =AlbertForPreTraining(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ,sentence_order_label=snake_case ,) self.parent.assertEqual(result.prediction_logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape ,(self.batch_size, config.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : List[Any] ,snake_case : int ,snake_case : str ,snake_case : Any ,snake_case : Dict ): SCREAMING_SNAKE_CASE =AlbertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : int ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ,snake_case : Optional[Any] ,snake_case : int ,snake_case : Optional[Any] ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =AlbertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,start_positions=snake_case ,end_positions=snake_case ,) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _lowerCAmelCase ( self : str ,snake_case : List[str] ,snake_case : Dict ,snake_case : Union[str, Any] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =AlbertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Any ,snake_case : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =AlbertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : Tuple ,snake_case : str ,snake_case : Any ,snake_case : Union[str, Any] ,snake_case : str ,snake_case : Any ,snake_case : Optional[Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =AlbertForMultipleChoice(config=snake_case ) model.to(snake_case ) 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( snake_case ,attention_mask=snake_case ,token_type_ids=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : 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 ) , ) =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 a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': AlbertModel, 'fill-mask': AlbertForMaskedLM, 'question-answering': AlbertForQuestionAnswering, 'text-classification': AlbertForSequenceClassification, 'token-classification': AlbertForTokenClassification, 'zero-shot': AlbertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = True def _lowerCAmelCase ( self : Tuple ,snake_case : Optional[int] ,snake_case : Any ,snake_case : List[Any]=False ): SCREAMING_SNAKE_CASE =super()._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) if return_labels: if model_class in get_values(snake_case ): SCREAMING_SNAKE_CASE =torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) ,dtype=torch.long ,device=snake_case ) SCREAMING_SNAKE_CASE =torch.zeros( self.model_tester.batch_size ,dtype=torch.long ,device=snake_case ) return inputs_dict def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =AlbertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : Dict ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : List[str] ): 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(*snake_case ) @slow def _lowerCAmelCase ( self : int ): for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =AlbertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =AlbertModel.from_pretrained('albert-base-v2' ) SCREAMING_SNAKE_CASE =torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 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(snake_case ,attention_mask=snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 11, 768) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] ,snake_case ,atol=1e-4 ) )
334
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
1
import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask _lowerCamelCase =logging.getLogger(__name__) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : List[str] ,snake_case : Dict=-1 ): # in NER datasets, the last column is usually reserved for NER label SCREAMING_SNAKE_CASE =label_idx def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[Any] ,snake_case : Union[Split, str] ): if isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =mode.value SCREAMING_SNAKE_CASE =os.path.join(snake_case ,f'{mode}.txt' ) SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =[] with open(snake_case ,encoding='utf-8' ) as f: SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[] for line in f: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' ,words=snake_case ,labels=snake_case ) ) guid_index += 1 SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[] else: SCREAMING_SNAKE_CASE =line.split(' ' ) words.append(splits[0] ) if len(snake_case ) > 1: labels.append(splits[self.label_idx].replace('\n' ,'' ) ) else: # Examples could have no label for mode = "test" labels.append('O' ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' ,words=snake_case ,labels=snake_case ) ) return examples def _lowerCAmelCase ( self : List[str] ,snake_case : TextIO ,snake_case : TextIO ,snake_case : List ): SCREAMING_SNAKE_CASE =0 for line in test_input_reader: if line.startswith('-DOCSTART-' ) or line == "" or line == "\n": writer.write(snake_case ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: SCREAMING_SNAKE_CASE =line.split()[0] + ' ' + preds_list[example_id].pop(0 ) + '\n' writer.write(snake_case ) else: logger.warning('Maximum sequence length exceeded: No prediction for \'%s\'.' ,line.split()[0] ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): if path: with open(snake_case ,'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() if "O" not in labels: SCREAMING_SNAKE_CASE =['O'] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ): # in CONLL2003 dataset chunk column is second-to-last super().__init__(label_idx=-2 ) def _lowerCAmelCase ( self : Tuple ,snake_case : str ): if path: with open(snake_case ,'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() if "O" not in labels: SCREAMING_SNAKE_CASE =['O'] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : str ,snake_case : Optional[int] ,snake_case : Union[Split, str] ): if isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =mode.value SCREAMING_SNAKE_CASE =os.path.join(snake_case ,f'{mode}.txt' ) SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =[] with open(snake_case ,encoding='utf-8' ) as f: for sentence in parse_incr(snake_case ): SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[] for token in sentence: words.append(token['form'] ) labels.append(token['upos'] ) assert len(snake_case ) == len(snake_case ) if words: examples.append(InputExample(guid=f'{mode}-{guid_index}' ,words=snake_case ,labels=snake_case ) ) guid_index += 1 return examples def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : TextIO ,snake_case : TextIO ,snake_case : List ): SCREAMING_SNAKE_CASE =0 for sentence in parse_incr(snake_case ): SCREAMING_SNAKE_CASE =preds_list[example_id] SCREAMING_SNAKE_CASE ='' for token in sentence: out += f'{token["form"]} ({token["upos"]}|{s_p.pop(0 )}) ' out += "\n" writer.write(snake_case ) example_id += 1 def _lowerCAmelCase ( self : Dict ,snake_case : str ): if path: with open(snake_case ,'r' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
334
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=False ): """simple docstring""" if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) and isinstance(lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =len(set_a.intersection(lowerCAmelCase_ ) ) if alternative_union: SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) + len(lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =len(set_a.union(lowerCAmelCase_ ) ) return intersection / union if isinstance(lowerCAmelCase_, (list, tuple) ) and isinstance(lowerCAmelCase_, (list, tuple) ): SCREAMING_SNAKE_CASE =[element for element in set_a if element in set_b] if alternative_union: SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) + len(lowerCAmelCase_ ) return len(lowerCAmelCase_ ) / union else: SCREAMING_SNAKE_CASE =set_a + [element for element in set_b if element not in set_a] return len(lowerCAmelCase_ ) / len(lowerCAmelCase_ ) return len(lowerCAmelCase_ ) / len(lowerCAmelCase_ ) return None if __name__ == "__main__": _lowerCamelCase ={"a", "b", "c", "d", "e"} _lowerCamelCase ={"c", "d", "e", "f", "h", "i"} print(jaccard_similarity(set_a, set_b))
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size 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 =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
import os from distutils.util import strtobool def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for e in env_keys: SCREAMING_SNAKE_CASE =int(os.environ.get(lowerCAmelCase_, -1 ) ) if val >= 0: return val return default def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=False ): """simple docstring""" SCREAMING_SNAKE_CASE =os.environ.get(lowerCAmelCase_, str(lowerCAmelCase_ ) ) return strtobool(lowerCAmelCase_ ) == 1 # As its name indicates `strtobool` actually returns an int... def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_="no" ): """simple docstring""" SCREAMING_SNAKE_CASE =os.environ.get(lowerCAmelCase_, str(lowerCAmelCase_ ) ) return value
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) _lowerCamelCase ={ "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig"], "processing_speech_to_text": ["Speech2TextProcessor"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["Speech2TextTokenizer"] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =["Speech2TextFeatureExtractor"] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFSpeech2TextForConditionalGeneration", "TFSpeech2TextModel", "TFSpeech2TextPreTrainedModel", ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST", "Speech2TextForConditionalGeneration", "Speech2TextModel", "Speech2TextPreTrainedModel", ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/data2vec-text-base": "https://huggingface.co/data2vec/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'data2vec-text' def __init__( self : int ,snake_case : Dict=30522 ,snake_case : str=768 ,snake_case : Any=12 ,snake_case : Tuple=12 ,snake_case : Optional[int]=3072 ,snake_case : List[Any]="gelu" ,snake_case : Optional[int]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : List[str]=512 ,snake_case : Optional[Any]=2 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : Optional[int]=1 ,snake_case : Dict=0 ,snake_case : Any=2 ,snake_case : List[str]="absolute" ,snake_case : str=True ,snake_case : int=None ,**snake_case : Union[str, Any] ,): super().__init__(pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,**snake_case ) 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 a_ ( lowerCamelCase_ ): """simple docstring""" @property def _lowerCAmelCase ( self : 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), ] )
334
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 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 =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_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.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , 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 a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : 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(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : 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(snake_case ) 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] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size 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 SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": 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(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) 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 =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
from maths.prime_factors import prime_factors def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if not isinstance(lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =F'Input value of [number={number}] must be an integer' raise TypeError(lowerCAmelCase_ ) if number < 1: raise ValueError('Input must be a positive integer' ) return -1 if len(prime_factors(lowerCAmelCase_ ) ) % 2 else 1 if __name__ == "__main__": import doctest doctest.testmod()
334
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 # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( 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 _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( 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 snake_case__ ( ): """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()
334
1
from __future__ import annotations from typing import Any class a_ : """simple docstring""" def __init__( self : str ,snake_case : int = 6 ): SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None self.create_linked_list(snake_case ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): SCREAMING_SNAKE_CASE =Node() SCREAMING_SNAKE_CASE =current_node SCREAMING_SNAKE_CASE =current_node SCREAMING_SNAKE_CASE =current_node for _ in range(1 ,snake_case ): SCREAMING_SNAKE_CASE =Node() SCREAMING_SNAKE_CASE =current_node SCREAMING_SNAKE_CASE =previous_node SCREAMING_SNAKE_CASE =current_node SCREAMING_SNAKE_CASE =self.front SCREAMING_SNAKE_CASE =previous_node def _lowerCAmelCase ( self : Union[str, Any] ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _lowerCAmelCase ( self : Dict ): self.check_can_perform_operation() return self.front.data if self.front else None def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): SCREAMING_SNAKE_CASE =self.rear.next if self.rear: SCREAMING_SNAKE_CASE =data def _lowerCAmelCase ( self : str ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: SCREAMING_SNAKE_CASE =self.front.data SCREAMING_SNAKE_CASE =None return data SCREAMING_SNAKE_CASE =self.front SCREAMING_SNAKE_CASE =old_front.next SCREAMING_SNAKE_CASE =old_front.data SCREAMING_SNAKE_CASE =None return data def _lowerCAmelCase ( self : Optional[Any] ): if self.is_empty(): raise Exception('Empty Queue' ) def _lowerCAmelCase ( self : List[Any] ): if self.rear and self.rear.next == self.front: raise Exception('Full Queue' ) class a_ : """simple docstring""" def __init__( self : str ): SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if __name__ == "__main__": import doctest doctest.testmod()
334
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
1
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: writer.write({'col_1': 'foo', 'col_2': 1}, key=1 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=2 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =value @pytest.mark.parametrize('optimized_int_type, expected_dtype', [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype', [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ], ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
1
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _lowerCamelCase =collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _lowerCamelCase ="https://storage.googleapis.com/cvdf-datasets/mnist/" def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ), dtype=lowerCAmelCase_ )[0] @deprecated(lowerCAmelCase_, 'Please use tf.data to implement this functionality.' ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" print('Extracting', f.name ) with gzip.GzipFile(fileobj=lowerCAmelCase_ ) as bytestream: SCREAMING_SNAKE_CASE =_readaa(lowerCAmelCase_ ) if magic != 2051: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) SCREAMING_SNAKE_CASE =_readaa(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =_readaa(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =_readaa(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =bytestream.read(rows * cols * num_images ) SCREAMING_SNAKE_CASE =numpy.frombuffer(lowerCAmelCase_, dtype=numpy.uinta ) SCREAMING_SNAKE_CASE =data.reshape(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, 1 ) return data @deprecated(lowerCAmelCase_, 'Please use tf.one_hot on tensors.' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =labels_dense.shape[0] SCREAMING_SNAKE_CASE =numpy.arange(lowerCAmelCase_ ) * num_classes SCREAMING_SNAKE_CASE =numpy.zeros((num_labels, num_classes) ) SCREAMING_SNAKE_CASE =1 return labels_one_hot @deprecated(lowerCAmelCase_, 'Please use tf.data to implement this functionality.' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=False, lowerCAmelCase_=10 ): """simple docstring""" print('Extracting', f.name ) with gzip.GzipFile(fileobj=lowerCAmelCase_ ) as bytestream: SCREAMING_SNAKE_CASE =_readaa(lowerCAmelCase_ ) if magic != 2049: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) SCREAMING_SNAKE_CASE =_readaa(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =bytestream.read(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =numpy.frombuffer(lowerCAmelCase_, dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(lowerCAmelCase_, lowerCAmelCase_ ) return labels class a_ : """simple docstring""" @deprecated( snake_case ,'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' ,) def __init__( self : Union[str, Any] ,snake_case : int ,snake_case : Union[str, Any] ,snake_case : Any=False ,snake_case : Optional[int]=False ,snake_case : Tuple=dtypes.floataa ,snake_case : List[Any]=True ,snake_case : Optional[int]=None ,): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =random_seed.get_seed(snake_case ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) SCREAMING_SNAKE_CASE =dtypes.as_dtype(snake_case ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: SCREAMING_SNAKE_CASE =10000 SCREAMING_SNAKE_CASE =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' SCREAMING_SNAKE_CASE =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 SCREAMING_SNAKE_CASE =images.reshape( images.shape[0] ,images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. SCREAMING_SNAKE_CASE =images.astype(numpy.floataa ) SCREAMING_SNAKE_CASE =numpy.multiply(snake_case ,1.0 / 255.0 ) SCREAMING_SNAKE_CASE =images SCREAMING_SNAKE_CASE =labels SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =0 @property def _lowerCAmelCase ( self : str ): return self._images @property def _lowerCAmelCase ( self : str ): return self._labels @property def _lowerCAmelCase ( self : Tuple ): return self._num_examples @property def _lowerCAmelCase ( self : Dict ): return self._epochs_completed def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : int ,snake_case : Tuple=False ,snake_case : Tuple=True ): if fake_data: SCREAMING_SNAKE_CASE =[1] * 784 SCREAMING_SNAKE_CASE =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(snake_case )], [fake_label for _ in range(snake_case )], ) SCREAMING_SNAKE_CASE =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: SCREAMING_SNAKE_CASE =numpy.arange(self._num_examples ) numpy.random.shuffle(snake_case ) SCREAMING_SNAKE_CASE =self.images[perma] SCREAMING_SNAKE_CASE =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch SCREAMING_SNAKE_CASE =self._num_examples - start SCREAMING_SNAKE_CASE =self._images[start : self._num_examples] SCREAMING_SNAKE_CASE =self._labels[start : self._num_examples] # Shuffle the data if shuffle: SCREAMING_SNAKE_CASE =numpy.arange(self._num_examples ) numpy.random.shuffle(snake_case ) SCREAMING_SNAKE_CASE =self.images[perm] SCREAMING_SNAKE_CASE =self.labels[perm] # Start next epoch SCREAMING_SNAKE_CASE =0 SCREAMING_SNAKE_CASE =batch_size - rest_num_examples SCREAMING_SNAKE_CASE =self._index_in_epoch SCREAMING_SNAKE_CASE =self._images[start:end] SCREAMING_SNAKE_CASE =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) ,axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) ,axis=0 ), ) else: self._index_in_epoch += batch_size SCREAMING_SNAKE_CASE =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(lowerCAmelCase_, 'Please write your own downloading logic.' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if not gfile.Exists(lowerCAmelCase_ ): gfile.MakeDirs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, lowerCAmelCase_ ) if not gfile.Exists(lowerCAmelCase_ ): urllib.request.urlretrieve(lowerCAmelCase_, lowerCAmelCase_ ) # noqa: S310 with gfile.GFile(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.size() print('Successfully downloaded', lowerCAmelCase_, lowerCAmelCase_, 'bytes.' ) return filepath @deprecated( lowerCAmelCase_, 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=False, lowerCAmelCase_=False, lowerCAmelCase_=dtypes.floataa, lowerCAmelCase_=True, lowerCAmelCase_=5000, lowerCAmelCase_=None, lowerCAmelCase_=DEFAULT_SOURCE_URL, ): """simple docstring""" if fake_data: def fake(): return _DataSet( [], [], fake_data=lowerCAmelCase_, one_hot=lowerCAmelCase_, dtype=lowerCAmelCase_, seed=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =fake() SCREAMING_SNAKE_CASE =fake() SCREAMING_SNAKE_CASE =fake() return _Datasets(train=lowerCAmelCase_, validation=lowerCAmelCase_, test=lowerCAmelCase_ ) if not source_url: # empty string check SCREAMING_SNAKE_CASE =DEFAULT_SOURCE_URL SCREAMING_SNAKE_CASE ='train-images-idx3-ubyte.gz' SCREAMING_SNAKE_CASE ='train-labels-idx1-ubyte.gz' SCREAMING_SNAKE_CASE ='t10k-images-idx3-ubyte.gz' SCREAMING_SNAKE_CASE ='t10k-labels-idx1-ubyte.gz' SCREAMING_SNAKE_CASE =_maybe_download( lowerCAmelCase_, lowerCAmelCase_, source_url + train_images_file ) with gfile.Open(lowerCAmelCase_, 'rb' ) as f: SCREAMING_SNAKE_CASE =_extract_images(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =_maybe_download( lowerCAmelCase_, lowerCAmelCase_, source_url + train_labels_file ) with gfile.Open(lowerCAmelCase_, 'rb' ) as f: SCREAMING_SNAKE_CASE =_extract_labels(lowerCAmelCase_, one_hot=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =_maybe_download( lowerCAmelCase_, lowerCAmelCase_, source_url + test_images_file ) with gfile.Open(lowerCAmelCase_, 'rb' ) as f: SCREAMING_SNAKE_CASE =_extract_images(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =_maybe_download( lowerCAmelCase_, lowerCAmelCase_, source_url + test_labels_file ) with gfile.Open(lowerCAmelCase_, 'rb' ) as f: SCREAMING_SNAKE_CASE =_extract_labels(lowerCAmelCase_, one_hot=lowerCAmelCase_ ) if not 0 <= validation_size <= len(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =( 'Validation size should be between 0 and ' F'{len(lowerCAmelCase_ )}. Received: {validation_size}.' ) raise ValueError(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =train_images[:validation_size] SCREAMING_SNAKE_CASE =train_labels[:validation_size] SCREAMING_SNAKE_CASE =train_images[validation_size:] SCREAMING_SNAKE_CASE =train_labels[validation_size:] SCREAMING_SNAKE_CASE ={'dtype': dtype, 'reshape': reshape, 'seed': seed} SCREAMING_SNAKE_CASE =_DataSet(lowerCAmelCase_, lowerCAmelCase_, **lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =_DataSet(lowerCAmelCase_, lowerCAmelCase_, **lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =_DataSet(lowerCAmelCase_, lowerCAmelCase_, **lowerCAmelCase_ ) return _Datasets(train=lowerCAmelCase_, validation=lowerCAmelCase_, test=lowerCAmelCase_ )
334
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size 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 SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": 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(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) 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 =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
1
from manim import * class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =Rectangle(height=0.5 ,width=0.5 ) SCREAMING_SNAKE_CASE =Rectangle(height=0.46 ,width=0.46 ).set_stroke(width=0 ) SCREAMING_SNAKE_CASE =Rectangle(height=0.25 ,width=0.25 ) SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 ) SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 ) SCREAMING_SNAKE_CASE =VGroup(snake_case ,snake_case ).arrange(snake_case ,buff=0 ) SCREAMING_SNAKE_CASE =Text('CPU' ,font_size=24 ) SCREAMING_SNAKE_CASE =Group(snake_case ,snake_case ).arrange(snake_case ,buff=0.5 ,aligned_edge=snake_case ) cpu.move_to([-2.5, -0.5, 0] ) self.add(snake_case ) SCREAMING_SNAKE_CASE =[mem.copy() for i in range(4 )] SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 ) SCREAMING_SNAKE_CASE =Text('GPU' ,font_size=24 ) SCREAMING_SNAKE_CASE =Group(snake_case ,snake_case ).arrange(snake_case ,buff=0.5 ,aligned_edge=snake_case ) gpu.move_to([-1, -1, 0] ) self.add(snake_case ) SCREAMING_SNAKE_CASE =[mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 ) SCREAMING_SNAKE_CASE =Text('Model' ,font_size=24 ) SCREAMING_SNAKE_CASE =Group(snake_case ,snake_case ).arrange(snake_case ,buff=0.5 ,aligned_edge=snake_case ) model.move_to([3, -1.0, 0] ) self.add(snake_case ) SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[] for i, rect in enumerate(snake_case ): SCREAMING_SNAKE_CASE =fill.copy().set_fill(snake_case ,opacity=0.8 ) target.move_to(snake_case ) model_arr.append(snake_case ) SCREAMING_SNAKE_CASE =Rectangle(height=0.46 ,width=0.46 ).set_stroke(width=0.0 ).set_fill(snake_case ,opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(snake_case ) self.add(*snake_case ,*snake_case ) SCREAMING_SNAKE_CASE =[meta_mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE =[meta_mem.copy() for i in range(6 )] SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 ) SCREAMING_SNAKE_CASE =VGroup(*snake_case ).arrange(snake_case ,buff=0 ) SCREAMING_SNAKE_CASE =VGroup(snake_case ,snake_case ).arrange(snake_case ,buff=0 ) SCREAMING_SNAKE_CASE =Text('Disk' ,font_size=24 ) SCREAMING_SNAKE_CASE =Group(snake_case ,snake_case ).arrange(snake_case ,buff=0.5 ,aligned_edge=snake_case ) disk.move_to([-4, -1.25, 0] ) self.add(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) SCREAMING_SNAKE_CASE =MarkupText( f'<b>Key:</b>\n\n<span fgcolor=\'{YELLOW}\'>●</span> Empty Model' ,font_size=18 ,) key_text.move_to([-5, 2.4, 0] ) self.add(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =MarkupText( f'<span fgcolor=\'{BLUE}\'>●</span> Checkpoint' ,font_size=18 ,) blue_text.next_to(snake_case ,DOWN * 2.4 ,aligned_edge=key_text.get_left() ) self.add(snake_case ) SCREAMING_SNAKE_CASE =MarkupText( f'Now watch as an input is passed through the model\nand how the memory is utilized and handled.' ,font_size=24 ,) step_a.move_to([2, 2, 0] ) self.play(Write(snake_case ) ) SCREAMING_SNAKE_CASE =Square(0.3 ) input.set_fill(snake_case ,opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] ,snake_case ,buff=0.5 ) self.play(Write(snake_case ) ) input.generate_target() input.target.next_to(model_arr[0] ,direction=snake_case ,buff=0.02 ) self.play(MoveToTarget(snake_case ) ) self.play(FadeOut(snake_case ) ) SCREAMING_SNAKE_CASE =Arrow(start=snake_case ,end=snake_case ,color=snake_case ,buff=0.5 ) a.next_to(model_arr[0].get_left() ,snake_case ,buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) SCREAMING_SNAKE_CASE =MarkupText( f'As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.' ,font_size=24 ,) step_a.move_to([2, 2, 0] ) self.play(Write(snake_case ,run_time=3 ) ) SCREAMING_SNAKE_CASE ={'run_time': 1, 'fade_in': True, 'fade_out': True, 'buff': 0.02} self.play( Write(snake_case ) ,Circumscribe(model_arr[0] ,color=snake_case ,**snake_case ) ,Circumscribe(model_cpu_arr[0] ,color=snake_case ,**snake_case ) ,Circumscribe(gpu_rect[0] ,color=snake_case ,**snake_case ) ,) self.play(MoveToTarget(model_cpu_arr[0] ) ) SCREAMING_SNAKE_CASE =a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.02 ,snake_case ,buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.02 ) SCREAMING_SNAKE_CASE =AnimationGroup( FadeOut(snake_case ,run_time=0.5 ) ,MoveToTarget(snake_case ,run_time=0.5 ) ,FadeIn(snake_case ,run_time=0.5 ) ,lag_ratio=0.2 ) self.play(snake_case ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: SCREAMING_SNAKE_CASE =0.7 self.play( Circumscribe(model_arr[i] ,**snake_case ) ,Circumscribe(cpu_left_col_base[i] ,**snake_case ) ,Circumscribe(cpu_left_col_base[i + 1] ,color=snake_case ,**snake_case ) ,Circumscribe(gpu_rect[0] ,color=snake_case ,**snake_case ) ,Circumscribe(model_arr[i + 1] ,color=snake_case ,**snake_case ) ,) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) ,MoveToTarget(model_cpu_arr[i + 1] ) ,) else: self.play( MoveToTarget(model_cpu_arr[i] ,run_time=0.7 ) ,MoveToTarget(model_cpu_arr[i + 1] ,run_time=0.7 ) ,) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() ,RIGHT + 0.02 ,buff=0.2 ) self.play( Circumscribe(model_arr[-1] ,color=snake_case ,**snake_case ) ,Circumscribe(cpu_left_col_base[-1] ,color=snake_case ,**snake_case ) ,Circumscribe(gpu_rect[0] ,color=snake_case ,**snake_case ) ,) self.play(MoveToTarget(model_cpu_arr[i] ) ) SCREAMING_SNAKE_CASE =a_c SCREAMING_SNAKE_CASE =a_c.copy() input.generate_target() input.target.next_to(model_base[-1] ,RIGHT + 0.02 ,buff=0.5 ) self.play( FadeOut(snake_case ) ,FadeOut(snake_case ,run_time=0.5 ) ,) SCREAMING_SNAKE_CASE =MarkupText(f'Inference on a model too large for GPU memory\nis successfully completed.' ,font_size=24 ) step_a.move_to([2, 2, 0] ) self.play(Write(snake_case ,run_time=3 ) ,MoveToTarget(snake_case ) ) self.wait()
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
import argparse import collections import os import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_table.py _lowerCamelCase ="src/transformers" _lowerCamelCase ="docs/source/en" _lowerCamelCase ="." def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r', encoding='utf-8', newline='\n' ) as f: SCREAMING_SNAKE_CASE =f.readlines() # Find the start prompt. SCREAMING_SNAKE_CASE =0 while not lines[start_index].startswith(lowerCAmelCase_ ): start_index += 1 start_index += 1 SCREAMING_SNAKE_CASE =start_index while not lines[end_index].startswith(lowerCAmelCase_ ): end_index += 1 end_index -= 1 while len(lines[start_index] ) <= 1: start_index += 1 while len(lines[end_index] ) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index] ), start_index, end_index, lines # Add here suffixes that are used to identify models, separated by | _lowerCamelCase ="Model|Encoder|Decoder|ForConditionalGeneration" # Regexes that match TF/Flax/PT model names. _lowerCamelCase =re.compile(R"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") _lowerCamelCase =re.compile(R"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. _lowerCamelCase =re.compile(R"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") # This is to make sure the transformers module imported is the one in the repo. _lowerCamelCase =direct_transformers_import(TRANSFORMERS_PATH) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', lowerCAmelCase_ ) return [m.group(0 ) for m in matches] def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =2 if text == '✅' or text == '❌' else len(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =(width - text_length) // 2 SCREAMING_SNAKE_CASE =width - text_length - left_indent return " " * left_indent + text + " " * right_indent def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE ={ name: config_maping_names[code] for code, name in transformers_module.MODEL_NAMES_MAPPING.items() if code in config_maping_names } SCREAMING_SNAKE_CASE ={name: config.replace('Config', '' ) for name, config in model_name_to_config.items()} # Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax. SCREAMING_SNAKE_CASE =collections.defaultdict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =collections.defaultdict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =collections.defaultdict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =collections.defaultdict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =collections.defaultdict(lowerCAmelCase_ ) # Let's lookup through all transformers object (once). for attr_name in dir(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =None if attr_name.endswith('Tokenizer' ): SCREAMING_SNAKE_CASE =slow_tokenizers SCREAMING_SNAKE_CASE =attr_name[:-9] elif attr_name.endswith('TokenizerFast' ): SCREAMING_SNAKE_CASE =fast_tokenizers SCREAMING_SNAKE_CASE =attr_name[:-13] elif _re_tf_models.match(lowerCAmelCase_ ) is not None: SCREAMING_SNAKE_CASE =tf_models SCREAMING_SNAKE_CASE =_re_tf_models.match(lowerCAmelCase_ ).groups()[0] elif _re_flax_models.match(lowerCAmelCase_ ) is not None: SCREAMING_SNAKE_CASE =flax_models SCREAMING_SNAKE_CASE =_re_flax_models.match(lowerCAmelCase_ ).groups()[0] elif _re_pt_models.match(lowerCAmelCase_ ) is not None: SCREAMING_SNAKE_CASE =pt_models SCREAMING_SNAKE_CASE =_re_pt_models.match(lowerCAmelCase_ ).groups()[0] if lookup_dict is not None: while len(lowerCAmelCase_ ) > 0: if attr_name in model_name_to_prefix.values(): SCREAMING_SNAKE_CASE =True break # Try again after removing the last word in the name SCREAMING_SNAKE_CASE =''.join(camel_case_split(lowerCAmelCase_ )[:-1] ) # Let's build that table! SCREAMING_SNAKE_CASE =list(model_name_to_config.keys() ) model_names.sort(key=str.lower ) SCREAMING_SNAKE_CASE =['Model', 'Tokenizer slow', 'Tokenizer fast', 'PyTorch support', 'TensorFlow support', 'Flax Support'] # We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side). SCREAMING_SNAKE_CASE =[len(lowerCAmelCase_ ) + 2 for c in columns] SCREAMING_SNAKE_CASE =max([len(lowerCAmelCase_ ) for name in model_names] ) + 2 # Build the table per se SCREAMING_SNAKE_CASE ='|' + '|'.join([_center_text(lowerCAmelCase_, lowerCAmelCase_ ) for c, w in zip(lowerCAmelCase_, lowerCAmelCase_ )] ) + '|\n' # Use ":-----:" format to center-aligned table cell texts table += "|" + "|".join([':' + '-' * (w - 2) + ':' for w in widths] ) + "|\n" SCREAMING_SNAKE_CASE ={True: '✅', False: '❌'} for name in model_names: SCREAMING_SNAKE_CASE =model_name_to_prefix[name] SCREAMING_SNAKE_CASE =[ name, check[slow_tokenizers[prefix]], check[fast_tokenizers[prefix]], check[pt_models[prefix]], check[tf_models[prefix]], check[flax_models[prefix]], ] table += "|" + "|".join([_center_text(lowerCAmelCase_, lowerCAmelCase_ ) for l, w in zip(lowerCAmelCase_, lowerCAmelCase_ )] ) + "|\n" return table def snake_case__ ( lowerCAmelCase_=False ): """simple docstring""" SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =_find_text_in_file( filename=os.path.join(lowerCAmelCase_, 'index.md' ), start_prompt='<!--This table is updated automatically from the auto modules', end_prompt='<!-- End table-->', ) SCREAMING_SNAKE_CASE =get_model_table_from_auto_modules() if current_table != new_table: if overwrite: with open(os.path.join(lowerCAmelCase_, 'index.md' ), 'w', encoding='utf-8', newline='\n' ) as f: f.writelines(lines[:start_index] + [new_table] + lines[end_index:] ) else: raise ValueError( 'The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.' ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") _lowerCamelCase =parser.parse_args() check_model_table(args.fix_and_overwrite)
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) 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 =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ="▁" _lowerCamelCase ={"vocab_file": "sentencepiece.bpe.model"} _lowerCamelCase ={ "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/blob/main/sentencepiece.bpe.model" ), } } _lowerCamelCase ={ "facebook/nllb-200-distilled-600M": 10_24, } # fmt: off _lowerCamelCase =["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = ['input_ids', 'attention_mask'] __UpperCAmelCase = [] __UpperCAmelCase = [] def __init__( self : List[str] ,snake_case : List[str] ,snake_case : Any="<s>" ,snake_case : str="</s>" ,snake_case : List[str]="</s>" ,snake_case : Dict="<s>" ,snake_case : Dict="<unk>" ,snake_case : List[str]="<pad>" ,snake_case : List[str]="<mask>" ,snake_case : Optional[int]=None ,snake_case : str=None ,snake_case : Dict=None ,snake_case : Optional[Dict[str, Any]] = None ,snake_case : Optional[int]=None ,snake_case : Tuple=False ,**snake_case : List[Any] ,): # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE =AddedToken(snake_case ,lstrip=snake_case ,rstrip=snake_case ) if isinstance(snake_case ,snake_case ) else mask_token SCREAMING_SNAKE_CASE ={} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE =legacy_behaviour super().__init__( bos_token=snake_case ,eos_token=snake_case ,unk_token=snake_case ,sep_token=snake_case ,cls_token=snake_case ,pad_token=snake_case ,mask_token=snake_case ,tokenizer_file=snake_case ,src_lang=snake_case ,tgt_lang=snake_case ,additional_special_tokens=snake_case ,sp_model_kwargs=self.sp_model_kwargs ,legacy_behaviour=snake_case ,**snake_case ,) SCREAMING_SNAKE_CASE =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(snake_case ) ) SCREAMING_SNAKE_CASE =vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | ---- | ---- | ---- | ---- | ---- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' # spm | '<unk>' | '<s>' | '</s>' | 'an' | '▁n' | '▁m' | '▁t' | '▁k' | '▁a' | '▁s' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE ={'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =len(self.sp_model ) SCREAMING_SNAKE_CASE ={ code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(snake_case ) } SCREAMING_SNAKE_CASE ={v: k for k, v in self.lang_code_to_id.items()} SCREAMING_SNAKE_CASE =len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) SCREAMING_SNAKE_CASE ={v: k for k, v in self.fairseq_tokens_to_ids.items()} SCREAMING_SNAKE_CASE =list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) SCREAMING_SNAKE_CASE =src_lang if src_lang is not None else 'eng_Latn' SCREAMING_SNAKE_CASE =self.lang_code_to_id[self._src_lang] SCREAMING_SNAKE_CASE =tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : Any ): SCREAMING_SNAKE_CASE =self.__dict__.copy() SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =self.sp_model.serialized_model_proto() return state def __setstate__( self : Dict ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _lowerCAmelCase ( self : Dict ): return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _lowerCAmelCase ( self : Tuple ): return self._src_lang @src_lang.setter def _lowerCAmelCase ( self : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _lowerCAmelCase ( self : str ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ,snake_case : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=snake_case ,token_ids_a=snake_case ,already_has_special_tokens=snake_case ) 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(snake_case )) + suffix_ones return prefix_ones + ([0] * len(snake_case )) + ([0] * len(snake_case )) + suffix_ones def _lowerCAmelCase ( self : str ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _lowerCAmelCase ( self : Any ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): 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 _lowerCAmelCase ( self : int ,snake_case : str ,snake_case : str ,snake_case : Optional[str] ,snake_case : Optional[str] ,**snake_case : Optional[Any] ): 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(snake_case ,add_special_tokens=snake_case ,return_tensors=snake_case ,**snake_case ) SCREAMING_SNAKE_CASE =self.convert_tokens_to_ids(snake_case ) SCREAMING_SNAKE_CASE =tgt_lang_id return inputs def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE ={self.convert_ids_to_tokens(snake_case ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _lowerCAmelCase ( self : Optional[Any] ,snake_case : str ): return self.sp_model.encode(snake_case ,out_type=snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Any ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE =self.sp_model.PieceToId(snake_case ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Any ): SCREAMING_SNAKE_CASE =''.join(snake_case ).replace(snake_case ,' ' ).strip() return out_string def _lowerCAmelCase ( self : Any ,snake_case : str ,snake_case : Optional[str] = None ): if not os.path.isdir(snake_case ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return SCREAMING_SNAKE_CASE =os.path.join( snake_case ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,snake_case ) elif not os.path.isfile(self.vocab_file ): with open(snake_case ,'wb' ) as fi: SCREAMING_SNAKE_CASE =self.sp_model.serialized_model_proto() fi.write(snake_case ) return (out_vocab_file,) def _lowerCAmelCase ( self : Optional[int] ,snake_case : List[str] ,snake_case : str = "eng_Latn" ,snake_case : Optional[List[str]] = None ,snake_case : str = "fra_Latn" ,**snake_case : Dict ,): SCREAMING_SNAKE_CASE =src_lang SCREAMING_SNAKE_CASE =tgt_lang return super().prepare_seqaseq_batch(snake_case ,snake_case ,**snake_case ) def _lowerCAmelCase ( self : List[str] ): return self.set_src_lang_special_tokens(self.src_lang ) def _lowerCAmelCase ( self : str ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _lowerCAmelCase ( self : List[Any] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.lang_code_to_id[src_lang] if self.legacy_behaviour: SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE =[self.cur_lang_code] SCREAMING_SNAKE_CASE =[self.eos_token_id] def _lowerCAmelCase ( self : str ,snake_case : str ): SCREAMING_SNAKE_CASE =self.lang_code_to_id[lang] if self.legacy_behaviour: SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =[self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE =[self.cur_lang_code] SCREAMING_SNAKE_CASE =[self.eos_token_id]
334
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
1
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =[ 'safety_checker/pytorch_model.bin', 'safety_checker/model.safetensors', 'vae/diffusion_pytorch_model.bin', 'vae/diffusion_pytorch_model.safetensors', 'text_encoder/pytorch_model.bin', 'text_encoder/model.safetensors', 'unet/diffusion_pytorch_model.bin', 'unet/diffusion_pytorch_model.safetensors', ] self.assertTrue(is_safetensors_compatible(snake_case ) ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =[ 'unet/diffusion_pytorch_model.bin', 'unet/diffusion_pytorch_model.safetensors', ] self.assertTrue(is_safetensors_compatible(snake_case ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =[ 'safety_checker/pytorch_model.bin', 'safety_checker/model.safetensors', 'vae/diffusion_pytorch_model.bin', 'vae/diffusion_pytorch_model.safetensors', 'text_encoder/pytorch_model.bin', 'text_encoder/model.safetensors', 'unet/diffusion_pytorch_model.bin', # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(snake_case ) ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =[ 'text_encoder/pytorch_model.bin', 'text_encoder/model.safetensors', ] self.assertTrue(is_safetensors_compatible(snake_case ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =[ 'safety_checker/pytorch_model.bin', 'safety_checker/model.safetensors', 'vae/diffusion_pytorch_model.bin', 'vae/diffusion_pytorch_model.safetensors', 'text_encoder/pytorch_model.bin', # Removed: 'text_encoder/model.safetensors', 'unet/diffusion_pytorch_model.bin', 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(snake_case ) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =[ 'safety_checker/pytorch_model.fp16.bin', 'safety_checker/model.fp16.safetensors', 'vae/diffusion_pytorch_model.fp16.bin', 'vae/diffusion_pytorch_model.fp16.safetensors', 'text_encoder/pytorch_model.fp16.bin', 'text_encoder/model.fp16.safetensors', 'unet/diffusion_pytorch_model.fp16.bin', 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE ='fp16' self.assertTrue(is_safetensors_compatible(snake_case ,variant=snake_case ) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =[ 'unet/diffusion_pytorch_model.fp16.bin', 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE ='fp16' self.assertTrue(is_safetensors_compatible(snake_case ,variant=snake_case ) ) def _lowerCAmelCase ( self : int ): # pass variant but use the non-variant filenames SCREAMING_SNAKE_CASE =[ 'unet/diffusion_pytorch_model.bin', 'unet/diffusion_pytorch_model.safetensors', ] SCREAMING_SNAKE_CASE ='fp16' self.assertTrue(is_safetensors_compatible(snake_case ,variant=snake_case ) ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =[ 'safety_checker/pytorch_model.fp16.bin', 'safety_checker/model.fp16.safetensors', 'vae/diffusion_pytorch_model.fp16.bin', 'vae/diffusion_pytorch_model.fp16.safetensors', 'text_encoder/pytorch_model.fp16.bin', 'text_encoder/model.fp16.safetensors', 'unet/diffusion_pytorch_model.fp16.bin', # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE ='fp16' self.assertFalse(is_safetensors_compatible(snake_case ,variant=snake_case ) ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =[ 'text_encoder/pytorch_model.fp16.bin', 'text_encoder/model.fp16.safetensors', ] SCREAMING_SNAKE_CASE ='fp16' self.assertTrue(is_safetensors_compatible(snake_case ,variant=snake_case ) ) def _lowerCAmelCase ( self : Any ): # pass variant but use the non-variant filenames SCREAMING_SNAKE_CASE =[ 'text_encoder/pytorch_model.bin', 'text_encoder/model.safetensors', ] SCREAMING_SNAKE_CASE ='fp16' self.assertTrue(is_safetensors_compatible(snake_case ,variant=snake_case ) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =[ 'safety_checker/pytorch_model.fp16.bin', 'safety_checker/model.fp16.safetensors', 'vae/diffusion_pytorch_model.fp16.bin', 'vae/diffusion_pytorch_model.fp16.safetensors', 'text_encoder/pytorch_model.fp16.bin', # 'text_encoder/model.fp16.safetensors', 'unet/diffusion_pytorch_model.fp16.bin', 'unet/diffusion_pytorch_model.fp16.safetensors', ] SCREAMING_SNAKE_CASE ='fp16' self.assertFalse(is_safetensors_compatible(snake_case ,variant=snake_case ) )
334
import copy import os import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np import pyarrow as pa import pyarrow.parquet as pq import pytest from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence from datasets.features import ArrayaD, ClassLabel, Features, Image, Value from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects from datasets.keyhash import DuplicatedKeysError, InvalidKeyError from .utils import require_pil class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : Any ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ) ,type=pa.intaa() ) def _lowerCAmelCase ( self : Union[str, Any] ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('bool' ) ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : int ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=Value('int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([1, 2, 3] ,try_type=Value('int32' ) ) ) self.assertEqual(arr.type ,pa.intaa() ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=Value('int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : Dict ): with self.assertRaises((TypeError, pa.lib.ArrowInvalid) ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,type=ArrayaD((1, 3) ,'int64' ) ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence([[[1, 2, 3]]] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,ArrayaDExtensionType((1, 3) ,'int64' ) ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =pa.array(TypedSequence(['foo', 'bar'] ,try_type=ArrayaD((1, 3) ,'int64' ) ) ) self.assertEqual(arr.type ,pa.string() ) @require_pil def _lowerCAmelCase ( self : int ): import PIL.Image SCREAMING_SNAKE_CASE =PIL.Image.fromarray(np.arange(10 ,dtype=np.uinta ).reshape(2 ,5 ) ) with patch( 'datasets.arrow_writer.cast_to_python_objects' ,side_effect=snake_case ) as mock_cast_to_python_objects: SCREAMING_SNAKE_CASE =pa.array(TypedSequence([{'path': None, 'bytes': B'image_bytes'}, pil_image] ,type=Image() ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =mock_cast_to_python_objects.call_args_list[-1] self.assertIn('optimize_list_casting' ,snake_case ) self.assertFalse(kwargs['optimize_list_casting'] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferReader(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_, pa.Buffer ) else pa.memory_map(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() assert len(pa_table.to_batches() ) == expected_num_chunks assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} del pa_table @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =Features({'labels': ClassLabel(names=['neg', 'pos'] )} ) with ArrowWriter(stream=lowerCAmelCase_, features=lowerCAmelCase_ ) as writer: writer.write({'labels': 0} ) writer.write({'labels': 1} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == features.arrow_schema assert writer._schema.metadata == features.arrow_schema.metadata SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pa.ipc.open_stream(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =f.read_all() SCREAMING_SNAKE_CASE =pa_table.schema assert pa_table.num_rows == 2 assert schema == features.arrow_schema assert schema.metadata == features.arrow_schema.metadata assert features == Features.from_arrow_schema(lowerCAmelCase_ ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=[1, 2] ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: with pytest.raises(lowerCAmelCase_ ): writer.write({'col_1': 'foo', 'col_2': 1}, key=10 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=10 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() @pytest.mark.parametrize('writer_batch_size', [None, 2, 10] ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter( stream=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_, hash_salt='split_name', check_duplicates=lowerCAmelCase_, ) as writer: writer.write({'col_1': 'foo', 'col_2': 1}, key=1 ) writer.write({'col_1': 'bar', 'col_2': 2}, key=2 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) writer.write_batch({'col_1': [], 'col_2': []} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_table(pa.Table.from_pydict({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) @pytest.mark.parametrize('writer_batch_size', [None, 1, 10] ) @pytest.mark.parametrize( 'fields', [None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() SCREAMING_SNAKE_CASE =pa.schema(lowerCAmelCase_ ) if fields else None with ArrowWriter(stream=lowerCAmelCase_, schema=lowerCAmelCase_, writer_batch_size=lowerCAmelCase_ ) as writer: writer.write_row(pa.Table.from_pydict({'col_1': ['foo'], 'col_2': [1]} ) ) writer.write_row(pa.Table.from_pydict({'col_1': ['bar'], 'col_2': [2]} ) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 if not fields: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(output.getvalue(), expected_num_chunks=num_examples if writer_batch_size == 1 else 1 ) def snake_case__ ( ): """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE ={'col_1': pa.string(), 'col_2': pa.intaa()} SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, 'test.arrow' ) with ArrowWriter(path=lowerCAmelCase_, schema=pa.schema(lowerCAmelCase_ ) ) as writer: writer.write_batch({'col_1': ['foo', 'bar'], 'col_2': [1, 2]} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert writer._schema == pa.schema(lowerCAmelCase_, metadata=writer._schema.metadata ) _check_output(lowerCAmelCase_, 1 ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if pa.types.is_list(lowerCAmelCase_ ): return get_base_dtype(arr_type.value_type ) else: return arr_type def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if isinstance(lst[0], lowerCAmelCase_ ): change_first_primitive_element_in_list(lst[0], lowerCAmelCase_ ) else: SCREAMING_SNAKE_CASE =value @pytest.mark.parametrize('optimized_int_type, expected_dtype', [(None, pa.intaa()), (Value('int32' ), pa.intaa())] ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(TypedSequence(lowerCAmelCase_, optimized_int_type=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype @pytest.mark.parametrize( 'col, expected_dtype', [ ('attention_mask', pa.inta()), ('special_tokens_mask', pa.inta()), ('token_type_ids', pa.inta()), ('input_ids', pa.intaa()), ('other', pa.intaa()), ], ) @pytest.mark.parametrize('sequence', [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == expected_dtype # not in range if col != "other": # avoids errors due to in-place modifications SCREAMING_SNAKE_CASE =copy.deepcopy(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1 change_first_primitive_element_in_list(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa.array(OptimizedTypedSequence(lowerCAmelCase_, col=lowerCAmelCase_ ) ) assert get_base_dtype(arr.type ) == pa.intaa() @pytest.mark.parametrize('raise_exception', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =str(tmp_path / 'dataset-train.arrow' ) try: with ArrowWriter(path=lowerCAmelCase_ ) as writer: if raise_exception: raise pa.lib.ArrowInvalid() else: writer.stream.close() except pa.lib.ArrowInvalid: pass finally: assert writer.stream.closed def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE ='mock://dataset-train.arrow' with ArrowWriter(path=lowerCAmelCase_, storage_options=mockfs.storage_options ) as writer: assert isinstance(writer._fs, type(lowerCAmelCase_ ) ) assert writer._fs.storage_options == mockfs.storage_options writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 assert mockfs.exists(lowerCAmelCase_ ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter(stream=lowerCAmelCase_ ) as writer: writer.write({'col_1': 'foo', 'col_2': 1} ) writer.write({'col_1': 'bar', 'col_2': 2} ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =writer.finalize() assert num_examples == 2 assert num_bytes > 0 SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]} @require_pil @pytest.mark.parametrize('embed_local_files', [False, True] ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" import PIL.Image SCREAMING_SNAKE_CASE =str(tmp_path / 'test_image_rgb.jpg' ) PIL.Image.fromarray(np.zeros((5, 5), dtype=np.uinta ) ).save(lowerCAmelCase_, format='png' ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ParquetWriter( stream=lowerCAmelCase_, features=Features({'image': Image()} ), embed_local_files=lowerCAmelCase_ ) as writer: writer.write({'image': image_path} ) writer.finalize() SCREAMING_SNAKE_CASE =pa.BufferReader(output.getvalue() ) SCREAMING_SNAKE_CASE =pq.read_table(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =pa_table.to_pydict() if embed_local_files: assert isinstance(out['image'][0]['path'], lowerCAmelCase_ ) with open(lowerCAmelCase_, 'rb' ) as f: assert out["image"][0]["bytes"] == f.read() else: assert out["image"][0]["path"] == image_path assert out["image"][0]["bytes"] is None def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =pa.schema([pa.field('col_1', pa.string(), nullable=lowerCAmelCase_ )] ) SCREAMING_SNAKE_CASE =pa.BufferOutputStream() with ArrowWriter(stream=lowerCAmelCase_ ) as writer: writer._build_writer(inferred_schema=lowerCAmelCase_ ) assert writer._schema == pa.schema([pa.field('col_1', pa.string() )] )
334
1
import math import flax.linen as nn import jax.numpy as jnp def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = 1, lowerCAmelCase_ = 1, lowerCAmelCase_ = 1.0e4, lowerCAmelCase_ = False, lowerCAmelCase_ = 1.0, ): """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F'Embedding dimension {embedding_dim} should be even' SCREAMING_SNAKE_CASE =float(embedding_dim // 2 ) SCREAMING_SNAKE_CASE =math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE =min_timescale * jnp.exp(jnp.arange(lowerCAmelCase_, dtype=jnp.floataa ) * -log_timescale_increment ) SCREAMING_SNAKE_CASE =jnp.expand_dims(lowerCAmelCase_, 1 ) * jnp.expand_dims(lowerCAmelCase_, 0 ) # scale embeddings SCREAMING_SNAKE_CASE =scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE =jnp.concatenate([jnp.cos(lowerCAmelCase_ ), jnp.sin(lowerCAmelCase_ )], axis=1 ) else: SCREAMING_SNAKE_CASE =jnp.concatenate([jnp.sin(lowerCAmelCase_ ), jnp.cos(lowerCAmelCase_ )], axis=1 ) SCREAMING_SNAKE_CASE =jnp.reshape(lowerCAmelCase_, [jnp.shape(lowerCAmelCase_ )[0], embedding_dim] ) return signal class a_ ( nn.Module ): """simple docstring""" __UpperCAmelCase = 32 __UpperCAmelCase = jnp.floataa @nn.compact def __call__( self : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =nn.Dense(self.time_embed_dim ,dtype=self.dtype ,name='linear_1' )(snake_case ) SCREAMING_SNAKE_CASE =nn.silu(snake_case ) SCREAMING_SNAKE_CASE =nn.Dense(self.time_embed_dim ,dtype=self.dtype ,name='linear_2' )(snake_case ) return temb class a_ ( nn.Module ): """simple docstring""" __UpperCAmelCase = 32 __UpperCAmelCase = False __UpperCAmelCase = 1 @nn.compact def __call__( self : Dict ,snake_case : List[str] ): return get_sinusoidal_embeddings( snake_case ,embedding_dim=self.dim ,flip_sin_to_cos=self.flip_sin_to_cos ,freq_shift=self.freq_shift )
334
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
1
import baseaa def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return baseaa.aaaencode(string.encode('utf-8' ) ) def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return baseaa.aaadecode(lowerCAmelCase_ ).decode('utf-8' ) if __name__ == "__main__": import doctest doctest.testmod()
334
import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={"vocab_file": "vocab.txt"} _lowerCamelCase ={ "vocab_file": { "facebook/esm2_t6_8M_UR50D": "https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt", "facebook/esm2_t12_35M_UR50D": "https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt", }, } _lowerCamelCase ={ "facebook/esm2_t6_8M_UR50D": 10_24, "facebook/esm2_t12_35M_UR50D": 10_24, } def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" with open(lowerCAmelCase_, 'r' ) as f: SCREAMING_SNAKE_CASE =f.read().splitlines() return [l.strip() for l in lines] class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = VOCAB_FILES_NAMES __UpperCAmelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase = ['input_ids', 'attention_mask'] def __init__( self : int ,snake_case : Dict ,snake_case : Dict="<unk>" ,snake_case : Optional[int]="<cls>" ,snake_case : Optional[int]="<pad>" ,snake_case : int="<mask>" ,snake_case : Optional[int]="<eos>" ,**snake_case : List[str] ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =load_vocab_file(snake_case ) SCREAMING_SNAKE_CASE =dict(enumerate(self.all_tokens ) ) SCREAMING_SNAKE_CASE ={tok: ind for ind, tok in enumerate(self.all_tokens )} SCREAMING_SNAKE_CASE =unk_token SCREAMING_SNAKE_CASE =cls_token SCREAMING_SNAKE_CASE =pad_token SCREAMING_SNAKE_CASE =mask_token SCREAMING_SNAKE_CASE =eos_token SCREAMING_SNAKE_CASE =self.all_tokens self._create_trie(self.unique_no_split_tokens ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : Dict ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Tuple ,snake_case : List[str] ,**snake_case : Any ): return text.split() def _lowerCAmelCase ( self : Optional[int] ,snake_case : str=False ): return len(self._id_to_token ) def _lowerCAmelCase ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def _lowerCAmelCase ( self : List[Any] ,snake_case : str ): return self._token_to_id.get(snake_case ,self._token_to_id.get(self.unk_token ) ) def _lowerCAmelCase ( self : Any ,snake_case : int ): return self._id_to_token.get(snake_case ,self.unk_token ) def _lowerCAmelCase ( self : List[str] ,snake_case : List[int] ,snake_case : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE =[self.cls_token_id] SCREAMING_SNAKE_CASE =[self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def _lowerCAmelCase ( self : Optional[int] ,snake_case : List ,snake_case : Optional[List] = None ,snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] SCREAMING_SNAKE_CASE =[1] + ([0] * len(snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(snake_case ) + [1] return mask def _lowerCAmelCase ( self : Optional[int] ,snake_case : Dict ,snake_case : Any ): SCREAMING_SNAKE_CASE =os.path.join(snake_case ,(filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(snake_case ,'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def _lowerCAmelCase ( self : int ): return self.get_vocab_size(with_added_tokens=snake_case ) def _lowerCAmelCase ( self : str ,snake_case : Union[List[str], List[AddedToken]] ,snake_case : bool = False ): return super()._add_tokens(snake_case ,special_tokens=snake_case )
334
1
from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) # TODO Update this _lowerCamelCase ={ "facebook/esm-1b": "https://huggingface.co/facebook/esm-1b/resolve/main/config.json", # See all ESM models at https://huggingface.co/models?filter=esm } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'esm' def __init__( self : List[Any] ,snake_case : Optional[Any]=None ,snake_case : Union[str, Any]=None ,snake_case : List[str]=None ,snake_case : str=768 ,snake_case : Optional[int]=12 ,snake_case : Any=12 ,snake_case : Optional[int]=3072 ,snake_case : List[str]=0.1 ,snake_case : str=0.1 ,snake_case : Tuple=1026 ,snake_case : Any=0.02 ,snake_case : List[Any]=1e-12 ,snake_case : Dict="absolute" ,snake_case : Tuple=True ,snake_case : Tuple=None ,snake_case : int=False ,snake_case : Optional[int]=False ,snake_case : Any=None ,snake_case : int=None ,**snake_case : List[str] ,): super().__init__(pad_token_id=snake_case ,mask_token_id=snake_case ,**snake_case ) 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_dropout_prob SCREAMING_SNAKE_CASE =attention_probs_dropout_prob SCREAMING_SNAKE_CASE =max_position_embeddings 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 =emb_layer_norm_before SCREAMING_SNAKE_CASE =token_dropout SCREAMING_SNAKE_CASE =is_folding_model if is_folding_model: if esmfold_config is None: logger.info('No esmfold_config supplied for folding model, using default values.' ) SCREAMING_SNAKE_CASE =EsmFoldConfig() elif isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =EsmFoldConfig(**snake_case ) SCREAMING_SNAKE_CASE =esmfold_config if vocab_list is None: logger.warning('No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!' ) SCREAMING_SNAKE_CASE =get_default_vocab_list() else: SCREAMING_SNAKE_CASE =vocab_list else: SCREAMING_SNAKE_CASE =None SCREAMING_SNAKE_CASE =None if self.esmfold_config is not None and getattr(self.esmfold_config ,'use_esm_attn_map' ,snake_case ): raise ValueError('The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!' ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =super().to_dict() if isinstance(self.esmfold_config ,snake_case ): SCREAMING_SNAKE_CASE =self.esmfold_config.to_dict() return output @dataclass class a_ : """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = 0 __UpperCAmelCase = True __UpperCAmelCase = False __UpperCAmelCase = 128 __UpperCAmelCase = None def _lowerCAmelCase ( self : int ): if self.trunk is None: SCREAMING_SNAKE_CASE =TrunkConfig() elif isinstance(self.trunk ,snake_case ): SCREAMING_SNAKE_CASE =TrunkConfig(**self.trunk ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =asdict(self ) SCREAMING_SNAKE_CASE =self.trunk.to_dict() return output @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 48 __UpperCAmelCase = 1_024 __UpperCAmelCase = 128 __UpperCAmelCase = 32 __UpperCAmelCase = 32 __UpperCAmelCase = 32 __UpperCAmelCase = 0 __UpperCAmelCase = 0 __UpperCAmelCase = False __UpperCAmelCase = 4 __UpperCAmelCase = 128 __UpperCAmelCase = None def _lowerCAmelCase ( self : str ): if self.structure_module is None: SCREAMING_SNAKE_CASE =StructureModuleConfig() elif isinstance(self.structure_module ,snake_case ): SCREAMING_SNAKE_CASE =StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f'`max_recycles` should be positive, got {self.max_recycles}.' ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( '`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got' f' {self.sequence_state_dim} and {self.sequence_state_dim}.' ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( '`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got' f' {self.pairwise_state_dim} and {self.pairwise_state_dim}.' ) SCREAMING_SNAKE_CASE =self.sequence_state_dim // self.sequence_head_width SCREAMING_SNAKE_CASE =self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( '`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got' f' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.' ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( '`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got' f' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.' ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f'`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.' ) if self.dropout >= 0.4: raise ValueError(f'`dropout` should not be greater than 0.4, got {self.dropout}.' ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =asdict(self ) SCREAMING_SNAKE_CASE =self.structure_module.to_dict() return output @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 384 __UpperCAmelCase = 128 __UpperCAmelCase = 16 __UpperCAmelCase = 128 __UpperCAmelCase = 12 __UpperCAmelCase = 4 __UpperCAmelCase = 8 __UpperCAmelCase = 0.1 __UpperCAmelCase = 8 __UpperCAmelCase = 1 __UpperCAmelCase = 2 __UpperCAmelCase = 7 __UpperCAmelCase = 10 __UpperCAmelCase = 1e-8 __UpperCAmelCase = 1e5 def _lowerCAmelCase ( self : List[Any] ): return asdict(self ) def snake_case__ ( ): """simple docstring""" return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : Any ,snake_case : Any ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : int ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Tuple ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 0 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def __call__( self : int ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ): raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE =timm.create_model(lowerCAmelCase_, pretrained=lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ResNetForImageClassification(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) assert torch.allclose(from_model(lowerCAmelCase_ ), our_model(lowerCAmelCase_ ).logits ), "The model logits don't match the original one." SCREAMING_SNAKE_CASE =F'resnet{"-".join(name.split("resnet" ) )}' print(lowerCAmelCase_ ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {checkpoint_name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1024, 2048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowerCAmelCase_, names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported resnet* architecture," " currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" def get_matched_characters(lowerCAmelCase_, lowerCAmelCase_ ) -> str: SCREAMING_SNAKE_CASE =[] SCREAMING_SNAKE_CASE =min(len(_stra ), len(_stra ) ) // 2 for i, l in enumerate(_stra ): SCREAMING_SNAKE_CASE =int(max(0, i - limit ) ) SCREAMING_SNAKE_CASE =int(min(i + limit + 1, len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =F'{_stra[0:_stra.index(lowerCAmelCase_ )]} {_stra[_stra.index(lowerCAmelCase_ ) + 1:]}' return "".join(lowerCAmelCase_ ) # matching characters SCREAMING_SNAKE_CASE =get_matched_characters(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_matched_characters(lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =len(lowerCAmelCase_ ) # transposition SCREAMING_SNAKE_CASE =( len([(ca, ca) for ca, ca in zip(lowerCAmelCase_, lowerCAmelCase_ ) if ca != ca] ) // 2 ) if not match_count: SCREAMING_SNAKE_CASE =0.0 else: SCREAMING_SNAKE_CASE =( 1 / 3 * ( match_count / len(lowerCAmelCase_ ) + match_count / len(lowerCAmelCase_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters SCREAMING_SNAKE_CASE =0 for ca, ca in zip(stra[:4], stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
334
import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_=7 ): """simple docstring""" SCREAMING_SNAKE_CASE =None if token is not None: SCREAMING_SNAKE_CASE ={'Accept': 'application/vnd.github+json', 'Authorization': F'Bearer {token}'} # The id of a workflow (not of a workflow run) SCREAMING_SNAKE_CASE ='636036' SCREAMING_SNAKE_CASE =F'https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs' # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += F'?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}' SCREAMING_SNAKE_CASE =requests.get(lowerCAmelCase_, headers=lowerCAmelCase_ ).json() return result["workflow_runs"] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_daily_ci_runs(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": SCREAMING_SNAKE_CASE =workflow_run['id'] break return workflow_run_id def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =get_last_daily_ci_runs(lowerCAmelCase_ ) if workflow_run_id is not None: SCREAMING_SNAKE_CASE =get_artifacts_links(worflow_run_id=lowerCAmelCase_, token=lowerCAmelCase_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: SCREAMING_SNAKE_CASE =artifacts_links[artifact_name] download_artifact( artifact_name=lowerCAmelCase_, artifact_url=lowerCAmelCase_, output_dir=lowerCAmelCase_, token=lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" get_last_daily_ci_artifacts(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={} for artifact_name in artifact_names: SCREAMING_SNAKE_CASE =os.path.join(lowerCAmelCase_, F'{artifact_name}.zip' ) if os.path.isfile(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE ={} with zipfile.ZipFile(lowerCAmelCase_ ) as z: for filename in z.namelist(): if not os.path.isdir(lowerCAmelCase_ ): # read the file with z.open(lowerCAmelCase_ ) as f: SCREAMING_SNAKE_CASE =f.read().decode('UTF-8' ) return results
334
1
def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def snake_case__ ( ): """simple docstring""" assert or_gate(0, 0 ) == 0 assert or_gate(0, 1 ) == 1 assert or_gate(1, 0 ) == 1 assert or_gate(1, 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
334
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple ,snake_case : Optional[int] ,snake_case : Dict=13 ,snake_case : str=7 ,snake_case : Dict=True ,snake_case : List[Any]=True ,snake_case : Dict=False ,snake_case : int=True ,snake_case : Dict=99 ,snake_case : int=32 ,snake_case : List[str]=5 ,snake_case : Optional[Any]=4 ,snake_case : Tuple=64 ,snake_case : List[Any]="gelu" ,snake_case : str=0.1 ,snake_case : str=0.1 ,snake_case : List[str]=512 ,snake_case : List[str]=16 ,snake_case : str=2 ,snake_case : Dict=0.02 ,snake_case : Optional[int]=3 ,snake_case : int=4 ,snake_case : Any=None ,snake_case : Union[str, Any]=2 ,snake_case : List[Any]=2 ,snake_case : Optional[int]=2 ,snake_case : Dict=2 ,snake_case : List[str]=4 ,snake_case : int=1 ,): 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 =q_groups SCREAMING_SNAKE_CASE =k_groups SCREAMING_SNAKE_CASE =v_groups SCREAMING_SNAKE_CASE =post_attention_groups SCREAMING_SNAKE_CASE =intermediate_groups SCREAMING_SNAKE_CASE =output_groups def _lowerCAmelCase ( self : Tuple ): 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 _lowerCAmelCase ( self : Optional[int] ): return SqueezeBertConfig( embedding_size=self.hidden_size ,vocab_size=self.vocab_size ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,attention_probs_dropout_prob=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,q_groups=self.q_groups ,k_groups=self.k_groups ,v_groups=self.v_groups ,post_attention_groups=self.post_attention_groups ,intermediate_groups=self.intermediate_groups ,output_groups=self.output_groups ,) def _lowerCAmelCase ( self : Dict ,snake_case : List[str] ,snake_case : Optional[Any] ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : str ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =SqueezeBertModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,snake_case ) SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Optional[int] ,snake_case : Union[str, Any] ,snake_case : List[Any] ,snake_case : int ,snake_case : Any ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =SqueezeBertForMaskedLM(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowerCAmelCase ( self : Tuple ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : List[str] ,snake_case : List[Any] ,snake_case : Dict ,snake_case : Optional[Any] ): SCREAMING_SNAKE_CASE =SqueezeBertForQuestionAnswering(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model( snake_case ,attention_mask=snake_case ,start_positions=snake_case ,end_positions=snake_case ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Any ,snake_case : Tuple ,snake_case : str ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ,snake_case : List[str] ,snake_case : Tuple ,snake_case : Dict ,snake_case : str ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =SqueezeBertForTokenClassification(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,attention_mask=snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Dict ,snake_case : str ,snake_case : Union[str, Any] ,snake_case : Union[str, Any] ,snake_case : Any ,snake_case : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.num_choices SCREAMING_SNAKE_CASE =SqueezeBertForMultipleChoice(config=snake_case ) model.to(snake_case ) 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( snake_case ,attention_mask=snake_case ,labels=snake_case ,) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_choices) ) def _lowerCAmelCase ( self : Union[str, 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)) =config_and_inputs SCREAMING_SNAKE_CASE ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCAmelCase = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = True __UpperCAmelCase = False def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =SqueezeBertModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,dim=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*snake_case ) def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*snake_case ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*snake_case ) @slow def _lowerCAmelCase ( self : str ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =SqueezeBertModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): """simple docstring""" @slow def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli' ) SCREAMING_SNAKE_CASE =torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]] ) SCREAMING_SNAKE_CASE =model(snake_case )[0] SCREAMING_SNAKE_CASE =torch.Size((1, 3) ) self.assertEqual(output.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(snake_case ,snake_case ,atol=1e-4 ) )
334
1
from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline _lowerCamelCase =logging.get_logger(__name__) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ,snake_case : Any ): if isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =[label.strip() for label in labels.split(',' ) if label.strip()] return labels def __call__( self : List[str] ,snake_case : Any ,snake_case : Dict ,snake_case : List[Any] ): if len(snake_case ) == 0 or len(snake_case ) == 0: raise ValueError('You must include at least one label and at least one sequence.' ) if hypothesis_template.format(labels[0] ) == hypothesis_template: raise ValueError( ( 'The provided hypothesis_template "{}" was not able to be formatted with the target labels. ' 'Make sure the passed template includes formatting syntax such as {{}} where the label should go.' ).format(snake_case ) ) if isinstance(snake_case ,snake_case ): SCREAMING_SNAKE_CASE =[sequences] SCREAMING_SNAKE_CASE =[] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(snake_case )] for label in labels] ) return sequence_pairs, sequences @add_end_docstrings(lowerCamelCase_ ) class a_ ( lowerCamelCase_ ): """simple docstring""" def __init__( self : int ,snake_case : Any=ZeroShotClassificationArgumentHandler() ,*snake_case : List[Any] ,**snake_case : Tuple ): SCREAMING_SNAKE_CASE =args_parser super().__init__(*snake_case ,**snake_case ) if self.entailment_id == -1: logger.warning( 'Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to ' '-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.' ) @property def _lowerCAmelCase ( self : Tuple ): for label, ind in self.model.config.labelaid.items(): if label.lower().startswith('entail' ): return ind return -1 def _lowerCAmelCase ( self : str ,snake_case : Tuple ,snake_case : Dict=True ,snake_case : List[str]=True ,snake_case : Union[str, Any]=TruncationStrategy.ONLY_FIRST ,**snake_case : int ): SCREAMING_SNAKE_CASE =self.framework if self.tokenizer.pad_token is None: # Override for tokenizers not supporting padding logger.error( 'Tokenizer was not supporting padding necessary for zero-shot, attempting to use ' ' `pad_token=eos_token`' ) SCREAMING_SNAKE_CASE =self.tokenizer.eos_token try: SCREAMING_SNAKE_CASE =self.tokenizer( snake_case ,add_special_tokens=snake_case ,return_tensors=snake_case ,padding=snake_case ,truncation=snake_case ,) except Exception as e: if "too short" in str(snake_case ): # tokenizers might yell that we want to truncate # to a value that is not even reached by the input. # In that case we don't want to truncate. # It seems there's not a really better way to catch that # exception. SCREAMING_SNAKE_CASE =self.tokenizer( snake_case ,add_special_tokens=snake_case ,return_tensors=snake_case ,padding=snake_case ,truncation=TruncationStrategy.DO_NOT_TRUNCATE ,) else: raise e return inputs def _lowerCAmelCase ( self : Dict ,**snake_case : List[Any] ): if kwargs.get('multi_class' ,snake_case ) is not None: SCREAMING_SNAKE_CASE =kwargs['multi_class'] logger.warning( 'The `multi_class` argument has been deprecated and renamed to `multi_label`. ' '`multi_class` will be removed in a future version of Transformers.' ) SCREAMING_SNAKE_CASE ={} if "candidate_labels" in kwargs: SCREAMING_SNAKE_CASE =self._args_parser._parse_labels(kwargs['candidate_labels'] ) if "hypothesis_template" in kwargs: SCREAMING_SNAKE_CASE =kwargs['hypothesis_template'] SCREAMING_SNAKE_CASE ={} if "multi_label" in kwargs: SCREAMING_SNAKE_CASE =kwargs['multi_label'] return preprocess_params, {}, postprocess_params def __call__( self : str ,snake_case : Union[str, List[str]] ,*snake_case : List[Any] ,**snake_case : Tuple ,): if len(snake_case ) == 0: pass elif len(snake_case ) == 1 and "candidate_labels" not in kwargs: SCREAMING_SNAKE_CASE =args[0] else: raise ValueError(f'Unable to understand extra arguments {args}' ) return super().__call__(snake_case ,**snake_case ) def _lowerCAmelCase ( self : Tuple ,snake_case : Tuple ,snake_case : Any=None ,snake_case : Union[str, Any]="This example is {}." ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self._args_parser(snake_case ,snake_case ,snake_case ) for i, (candidate_label, sequence_pair) in enumerate(zip(snake_case ,snake_case ) ): SCREAMING_SNAKE_CASE =self._parse_and_tokenize([sequence_pair] ) yield { "candidate_label": candidate_label, "sequence": sequences[0], "is_last": i == len(snake_case ) - 1, **model_input, } def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ): SCREAMING_SNAKE_CASE =inputs['candidate_label'] SCREAMING_SNAKE_CASE =inputs['sequence'] SCREAMING_SNAKE_CASE ={k: inputs[k] for k in self.tokenizer.model_input_names} SCREAMING_SNAKE_CASE =self.model(**snake_case ) SCREAMING_SNAKE_CASE ={ 'candidate_label': candidate_label, 'sequence': sequence, 'is_last': inputs['is_last'], **outputs, } return model_outputs def _lowerCAmelCase ( self : Any ,snake_case : Union[str, Any] ,snake_case : List[Any]=False ): SCREAMING_SNAKE_CASE =[outputs['candidate_label'] for outputs in model_outputs] SCREAMING_SNAKE_CASE =[outputs['sequence'] for outputs in model_outputs] SCREAMING_SNAKE_CASE =np.concatenate([output['logits'].numpy() for output in model_outputs] ) SCREAMING_SNAKE_CASE =logits.shape[0] SCREAMING_SNAKE_CASE =len(snake_case ) SCREAMING_SNAKE_CASE =N // n SCREAMING_SNAKE_CASE =logits.reshape((num_sequences, n, -1) ) if multi_label or len(snake_case ) == 1: # softmax over the entailment vs. contradiction dim for each label independently SCREAMING_SNAKE_CASE =self.entailment_id SCREAMING_SNAKE_CASE =-1 if entailment_id == 0 else 0 SCREAMING_SNAKE_CASE =reshaped_outputs[..., [contradiction_id, entailment_id]] SCREAMING_SNAKE_CASE =np.exp(snake_case ) / np.exp(snake_case ).sum(-1 ,keepdims=snake_case ) SCREAMING_SNAKE_CASE =scores[..., 1] else: # softmax the "entailment" logits over all candidate labels SCREAMING_SNAKE_CASE =reshaped_outputs[..., self.entailment_id] SCREAMING_SNAKE_CASE =np.exp(snake_case ) / np.exp(snake_case ).sum(-1 ,keepdims=snake_case ) SCREAMING_SNAKE_CASE =list(reversed(scores[0].argsort() ) ) return { "sequence": sequences[0], "labels": [candidate_labels[i] for i in top_inds], "scores": scores[0, top_inds].tolist(), }
334
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = None __UpperCAmelCase = None @property def _lowerCAmelCase ( self : List[Any] ): return self.feat_extract_tester.prepare_feat_extract_dict() def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(snake_case ,'feature_size' ) ) self.assertTrue(hasattr(snake_case ,'sampling_rate' ) ) self.assertTrue(hasattr(snake_case ,'padding_value' ) ) def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(snake_case ) == len(snake_case ) for x, y in zip(snake_case ,processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(equal_length=snake_case ) SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) SCREAMING_SNAKE_CASE =processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE =batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Optional[Any]=False ): def _inputs_have_equal_length(snake_case : Dict ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : str ,snake_case : Dict ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.seq_length_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.max_seq_length + pad_diff SCREAMING_SNAKE_CASE =self.feat_extract_tester.min_seq_length SCREAMING_SNAKE_CASE =self.feat_extract_tester.batch_size SCREAMING_SNAKE_CASE =self.feat_extract_tester.feature_size # test padding for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,pad_to_multiple_of=10 ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(all(len(snake_case ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) SCREAMING_SNAKE_CASE =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(snake_case ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct SCREAMING_SNAKE_CASE =(np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int]=False ): def _inputs_have_equal_length(snake_case : str ): SCREAMING_SNAKE_CASE =len(input[0] ) for input_slice in input[1:]: if len(snake_case ) != length: return False return True def _inputs_are_equal(snake_case : Tuple ,snake_case : Optional[Any] ): if len(snake_case ) != len(snake_case ): return False for input_slice_a, input_slice_a in zip(snake_case ,snake_case ): if not np.allclose(np.asarray(snake_case ) ,np.asarray(snake_case ) ,atol=1e-3 ): return False return True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common(numpify=snake_case ) SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) # truncate to smallest SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to smallest with np SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) # truncate to middle SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ,return_tensors='np' ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=snake_case ) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) SCREAMING_SNAKE_CASE =input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertTrue(_inputs_are_equal(snake_case ,snake_case ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(snake_case ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='longest' ,truncation=snake_case )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(snake_case ): feat_extract.pad(snake_case ,padding='max_length' ,truncation=snake_case )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy SCREAMING_SNAKE_CASE =12 SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,truncation=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=snake_case ,) SCREAMING_SNAKE_CASE =input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of SCREAMING_SNAKE_CASE =len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: SCREAMING_SNAKE_CASE =((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(snake_case ) ) self.assertFalse(_inputs_have_equal_length(snake_case ) ) def _lowerCAmelCase ( self : Optional[int] ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : Tuple ): self._check_padding(numpify=snake_case ) def _lowerCAmelCase ( self : List[str] ): self._check_truncation(numpify=snake_case ) def _lowerCAmelCase ( self : int ): self._check_truncation(numpify=snake_case ) @require_torch def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =feat_extract.pad(snake_case ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.feat_extract_dict SCREAMING_SNAKE_CASE =True SCREAMING_SNAKE_CASE =self.feature_extraction_class(**snake_case ) SCREAMING_SNAKE_CASE =self.feat_extract_tester.prepare_inputs_for_common() SCREAMING_SNAKE_CASE =[len(snake_case ) for x in speech_inputs] SCREAMING_SNAKE_CASE =feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE =BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE =min(snake_case ) SCREAMING_SNAKE_CASE =feat_extract.pad( snake_case ,padding='max_length' ,max_length=snake_case ,truncation=snake_case ,return_tensors='np' ) self.assertIn('attention_mask' ,snake_case ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
334
1
from __future__ import annotations _lowerCamelCase =list[list[int]] # assigning initial values to the grid _lowerCamelCase =[ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution _lowerCamelCase =[ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if location := find_empty_location(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1, 10 ): if is_safe(lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =digit if sudoku(lowerCAmelCase_ ) is not None: return grid SCREAMING_SNAKE_CASE =0 return None def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" for row in grid: for cell in row: print(lowerCAmelCase_, end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") _lowerCamelCase =sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
334
from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase =2_00 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase =50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase =0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 10_00)) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =random.randint(0, len(lowerCAmelCase_ ) - 1 ) SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] SCREAMING_SNAKE_CASE =parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =list(lowerCAmelCase_ ) if random.uniform(0, 1 ) < MUTATION_PROBABILITY: SCREAMING_SNAKE_CASE =random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" SCREAMING_SNAKE_CASE =[] # Generate more children proportionally to the fitness score. SCREAMING_SNAKE_CASE =int(parent_a[1] * 100 ) + 1 SCREAMING_SNAKE_CASE =10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): SCREAMING_SNAKE_CASE =population_score[random.randint(0, lowerCAmelCase_ )][0] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =crossover(parent_a[0], lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_, lowerCAmelCase_ ) ) return pop def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True ): """simple docstring""" if N_POPULATION < N_SELECTED: SCREAMING_SNAKE_CASE =F'{N_POPULATION} must be bigger than {N_SELECTED}' raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. SCREAMING_SNAKE_CASE =sorted({c for c in target if c not in genes} ) if not_in_genes_list: SCREAMING_SNAKE_CASE =F'{not_in_genes_list} is not in genes list, evolution cannot converge' raise ValueError(lowerCAmelCase_ ) # Generate random starting population. SCREAMING_SNAKE_CASE =[] for _ in range(lowerCAmelCase_ ): population.append(''.join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. SCREAMING_SNAKE_CASE =[evaluate(lowerCAmelCase_, lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. SCREAMING_SNAKE_CASE =sorted(lowerCAmelCase_, key=lambda lowerCAmelCase_ : x[1], reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( F'\nGeneration: {generation}' F'\nTotal Population:{total_population}' F'\nBest score: {population_score[0][1]}' F'\nBest string: {population_score[0][0]}' ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. SCREAMING_SNAKE_CASE =population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. SCREAMING_SNAKE_CASE =[ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )], lowerCAmelCase_, lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase =( "This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!" ) _lowerCamelCase =list( " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm" "nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\" ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase =basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" if p < 2: raise ValueError('p should not be less than 2!' ) elif p == 2: return True SCREAMING_SNAKE_CASE =4 SCREAMING_SNAKE_CASE =(1 << p) - 1 for _ in range(p - 2 ): SCREAMING_SNAKE_CASE =((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
334
import os import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from huggingface_hub.file_download import http_get from requests.exceptions import HTTPError from transformers import ( AlbertTokenizer, AutoTokenizer, BertTokenizer, BertTokenizerFast, GPTaTokenizerFast, is_tokenizers_available, ) from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers from transformers.tokenization_utils import Trie sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Dict ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() @require_tokenizers def _lowerCAmelCase ( self : Optional[Any] ): # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE =mock.Mock() SCREAMING_SNAKE_CASE =500 SCREAMING_SNAKE_CASE ={} SCREAMING_SNAKE_CASE =HTTPError SCREAMING_SNAKE_CASE ={} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('requests.Session.request' ,return_value=snake_case ) as mock_head: SCREAMING_SNAKE_CASE =GPTaTokenizerFast.from_pretrained('gpt2' ) # This check we did call the fake head request mock_head.assert_called() def _lowerCAmelCase ( self : Union[str, Any] ): # This test is for deprecated behavior and can be removed in v5 try: SCREAMING_SNAKE_CASE =tempfile.mktemp() with open(snake_case ,'wb' ) as f: http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ,snake_case ) SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained(snake_case ) finally: os.remove(snake_case ) # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in # the current folder and have the right name. if os.path.isfile('tokenizer.json' ): # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. return try: with open('tokenizer.json' ,'wb' ) as f: http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json' ,snake_case ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000 self.assertEqual(tokenizer.vocab_size ,1000 ) # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. finally: os.remove('tokenizer.json' ) def _lowerCAmelCase ( self : int ): # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE =AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model' ) @is_staging_test class a_ ( unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou'] @classmethod def _lowerCAmelCase ( cls : List[Any] ): SCREAMING_SNAKE_CASE =TOKEN HfFolder.save_token(snake_case ) @classmethod def _lowerCAmelCase ( cls : Tuple ): try: delete_repo(token=cls._token ,repo_id='test-tokenizer' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='valid_org/test-tokenizer-org' ) except HTTPError: pass try: delete_repo(token=cls._token ,repo_id='test-dynamic-tokenizer' ) except HTTPError: pass def _lowerCAmelCase ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('test-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='test-tokenizer' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(snake_case ,repo_id='test-tokenizer' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained(f'{USER}/test-tokenizer' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) def _lowerCAmelCase ( self : Optional[Any] ): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizer(snake_case ) tokenizer.push_to_hub('valid_org/test-tokenizer-org' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) # Reset repo delete_repo(token=self._token ,repo_id='valid_org/test-tokenizer-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained( snake_case ,repo_id='valid_org/test-tokenizer-org' ,push_to_hub=snake_case ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('valid_org/test-tokenizer-org' ) self.assertDictEqual(new_tokenizer.vocab ,tokenizer.vocab ) @require_tokenizers def _lowerCAmelCase ( self : str ): CustomTokenizer.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =CustomTokenizer(snake_case ) # No fast custom tokenizer tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) # Fast and slow custom tokenizer CustomTokenizerFast.register_for_auto_class() with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE =os.path.join(snake_case ,'vocab.txt' ) with open(snake_case ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens] ) ) SCREAMING_SNAKE_CASE =BertTokenizerFast.from_pretrained(snake_case ) bert_tokenizer.save_pretrained(snake_case ) SCREAMING_SNAKE_CASE =CustomTokenizerFast.from_pretrained(snake_case ) tokenizer.push_to_hub('test-dynamic-tokenizer' ,use_auth_token=self._token ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer' ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizerFast' ) SCREAMING_SNAKE_CASE =AutoTokenizer.from_pretrained( f'{USER}/test-dynamic-tokenizer' ,use_fast=snake_case ,trust_remote_code=snake_case ) # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module self.assertEqual(tokenizer.__class__.__name__ ,'CustomTokenizer' ) class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('Hello 友達' ) self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}} ) trie.add('Hello' ) trie.data self.assertEqual(trie.data ,{'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}} ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE =Trie() self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS] This is a extra_id_100'] ) trie.add('[CLS]' ) trie.add('extra_id_1' ) trie.add('extra_id_100' ) self.assertEqual(trie.split('[CLS] This is a extra_id_100' ) ,['[CLS]', ' This is a ', 'extra_id_100'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) self.assertEqual(trie.split('ABC' ) ,['A', 'BC'] ) self.assertEqual(trie.split('BCA' ) ,['BC', 'A'] ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =Trie() trie.add('TOKEN]' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('A' ) trie.add('P' ) trie.add('[SPECIAL_TOKEN]' ) self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]' ) ,['This is something ', '[SPECIAL_TOKEN]'] ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =Trie() trie.add('AB' ) trie.add('B' ) trie.add('C' ) self.assertEqual(trie.split('ABC' ) ,['AB', 'C'] ) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =Trie() trie.add('ABC' ) trie.add('B' ) trie.add('CD' ) self.assertEqual(trie.split('ABCD' ) ,['ABC', 'D'] ) def _lowerCAmelCase ( self : Optional[Any] ): # Even if the offsets are wrong, we necessarily output correct string # parts. SCREAMING_SNAKE_CASE =Trie() SCREAMING_SNAKE_CASE =trie.cut_text('ABC' ,[0, 0, 2, 1, 2, 3] ) self.assertEqual(snake_case ,['AB', 'C'] )
334
1
from collections import deque class a_ : """simple docstring""" def __init__( self : List[str] ,snake_case : str ,snake_case : int ,snake_case : int ): SCREAMING_SNAKE_CASE =process_name # process name SCREAMING_SNAKE_CASE =arrival_time # arrival time of the process # completion time of finished process or last interrupted time SCREAMING_SNAKE_CASE =arrival_time SCREAMING_SNAKE_CASE =burst_time # remaining burst time SCREAMING_SNAKE_CASE =0 # total time of the process wait in ready queue SCREAMING_SNAKE_CASE =0 # time from arrival time to completion time class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : int ,snake_case : list[int] ,snake_case : deque[Process] ,snake_case : int ,): # total number of mlfq's queues SCREAMING_SNAKE_CASE =number_of_queues # time slice of queues that round robin algorithm applied SCREAMING_SNAKE_CASE =time_slices # unfinished process is in this ready_queue SCREAMING_SNAKE_CASE =queue # current time SCREAMING_SNAKE_CASE =current_time # finished process is in this sequence queue SCREAMING_SNAKE_CASE =deque() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =[] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def _lowerCAmelCase ( self : Dict ,snake_case : list[Process] ): SCREAMING_SNAKE_CASE =[] for i in range(len(snake_case ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def _lowerCAmelCase ( self : str ,snake_case : list[Process] ): SCREAMING_SNAKE_CASE =[] for i in range(len(snake_case ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def _lowerCAmelCase ( self : Dict ,snake_case : list[Process] ): SCREAMING_SNAKE_CASE =[] for i in range(len(snake_case ) ): completion_times.append(queue[i].stop_time ) return completion_times def _lowerCAmelCase ( self : str ,snake_case : deque[Process] ): return [q.burst_time for q in queue] def _lowerCAmelCase ( self : str ,snake_case : Process ): process.waiting_time += self.current_time - process.stop_time return process.waiting_time def _lowerCAmelCase ( self : Any ,snake_case : deque[Process] ): SCREAMING_SNAKE_CASE =deque() # sequence deque of finished process while len(snake_case ) != 0: SCREAMING_SNAKE_CASE =ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(snake_case ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 SCREAMING_SNAKE_CASE =0 # set the process's turnaround time because it is finished SCREAMING_SNAKE_CASE =self.current_time - cp.arrival_time # set the completion time SCREAMING_SNAKE_CASE =self.current_time # add the process to queue that has finished queue finished.append(snake_case ) self.finish_queue.extend(snake_case ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def _lowerCAmelCase ( self : int ,snake_case : deque[Process] ,snake_case : int ): SCREAMING_SNAKE_CASE =deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(snake_case ) ): SCREAMING_SNAKE_CASE =ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(snake_case ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time SCREAMING_SNAKE_CASE =self.current_time # locate the process behind the queue because it is not finished ready_queue.append(snake_case ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished SCREAMING_SNAKE_CASE =0 # set the finish time SCREAMING_SNAKE_CASE =self.current_time # update the process' turnaround time because it is finished SCREAMING_SNAKE_CASE =self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(snake_case ) self.finish_queue.extend(snake_case ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def _lowerCAmelCase ( self : List[Any] ): # all queues except last one have round_robin algorithm for i in range(self.number_of_queues - 1 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.round_robin( self.ready_queue ,self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest _lowerCamelCase =Process("P1", 0, 53) _lowerCamelCase =Process("P2", 0, 17) _lowerCamelCase =Process("P3", 0, 68) _lowerCamelCase =Process("P4", 0, 24) _lowerCamelCase =3 _lowerCamelCase =[17, 25] _lowerCamelCase =deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={"queue": deque([Pa, Pa, Pa, Pa])}) _lowerCamelCase =Process("P1", 0, 53) _lowerCamelCase =Process("P2", 0, 17) _lowerCamelCase =Process("P3", 0, 68) _lowerCamelCase =Process("P4", 0, 24) _lowerCamelCase =3 _lowerCamelCase =[17, 25] _lowerCamelCase =deque([Pa, Pa, Pa, Pa]) _lowerCamelCase =MLFQ(number_of_queues, time_slices, queue, 0) _lowerCamelCase =mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( f'waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print completion times of processes(P1, P2, P3, P4) print( f'completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print total turnaround times of processes(P1, P2, P3, P4) print( f'turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}' ) # print sequence of finished processes print( f'sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}' )
334
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase =[ ("bert.bert", "visual_bert"), ("bert.cls", "cls"), ("bert.classifier", "cls"), ("token_type_embeddings_visual", "visual_token_type_embeddings"), ("position_embeddings_visual", "visual_position_embeddings"), ("projection", "visual_projection"), ] _lowerCamelCase =[ "nlvr2_coco_pre_trained.th", "nlvr2_fine_tuned.th", "nlvr2_pre_trained.th", "vcr_coco_pre_train.th", "vcr_fine_tune.th", "vcr_pre_train.th", "vqa_coco_pre_trained.th", "vqa_fine_tuned.th", "vqa_pre_trained.th", ] def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =torch.load(lowerCAmelCase_, map_location='cpu' ) return sd def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE =OrderedDict() SCREAMING_SNAKE_CASE =torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE =key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE =new_key.replace(name_pair[0], name_pair[1] ) SCREAMING_SNAKE_CASE =d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE =new_d['cls.predictions.bias'] return new_d @torch.no_grad() def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" assert ( checkpoint_path.split('/' )[-1] in ACCEPTABLE_CHECKPOINTS ), F'The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE ='pretraining' if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 1024} else: raise NotImplementedError(F'No implementation found for `{checkpoint_path}`.' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 512} SCREAMING_SNAKE_CASE ='multichoice' elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048} SCREAMING_SNAKE_CASE ='vqa_advanced' elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE ={'visual_embedding_dim': 2048, 'num_labels': 3129} SCREAMING_SNAKE_CASE ='vqa' elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE ={ 'visual_embedding_dim': 1024, 'num_labels': 2, } SCREAMING_SNAKE_CASE ='nlvr' SCREAMING_SNAKE_CASE =VisualBertConfig(**lowerCAmelCase_ ) # Load State Dict SCREAMING_SNAKE_CASE =load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =get_new_dict(lowerCAmelCase_, lowerCAmelCase_ ) if model_type == "pretraining": SCREAMING_SNAKE_CASE =VisualBertForPreTraining(lowerCAmelCase_ ) elif model_type == "vqa": SCREAMING_SNAKE_CASE =VisualBertForQuestionAnswering(lowerCAmelCase_ ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE =VisualBertForVisualReasoning(lowerCAmelCase_ ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE =VisualBertForMultipleChoice(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) # Save Checkpoints Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument("orig_checkpoint_path", type=str, help="A path to .th on local filesystem.") parser.add_argument("pytorch_dump_folder_path", type=str, help="Path to the output PyTorch model.") _lowerCamelCase =parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
334
1
import pickle import unittest import torch from accelerate import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils import require_cpu @require_cpu class a_ ( unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self : Any ): SCREAMING_SNAKE_CASE =torch.nn.Linear(10 ,10 ) SCREAMING_SNAKE_CASE =torch.optim.SGD(model.parameters() ,0.1 ) SCREAMING_SNAKE_CASE =Accelerator() SCREAMING_SNAKE_CASE =accelerator.prepare(snake_case ) try: pickle.loads(pickle.dumps(snake_case ) ) except Exception as e: self.fail(f'Accelerated optimizer pickling failed with {e}' ) AcceleratorState._reset_state()
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/nllb-moe-54B": "https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'nllb-moe' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : Optional[int]=128112 ,snake_case : Any=1024 ,snake_case : List[str]=12 ,snake_case : Optional[int]=4096 ,snake_case : List[str]=16 ,snake_case : Optional[Any]=12 ,snake_case : Optional[Any]=4096 ,snake_case : List[Any]=16 ,snake_case : Optional[Any]=0.05 ,snake_case : str=0.05 ,snake_case : Optional[int]=True ,snake_case : Tuple=True ,snake_case : Optional[Any]="relu" ,snake_case : Any=1024 ,snake_case : List[Any]=0.1 ,snake_case : List[Any]=0.1 ,snake_case : Optional[Any]=0.0 ,snake_case : List[Any]=0.02 ,snake_case : Any=2 ,snake_case : Dict=True ,snake_case : Tuple=False ,snake_case : Any="float32" ,snake_case : Tuple=False ,snake_case : List[Any]=128 ,snake_case : Tuple=64 ,snake_case : List[Any]=4 ,snake_case : List[Any]=4 ,snake_case : List[Any]=0.001 ,snake_case : int=0.001 ,snake_case : Tuple="all" ,snake_case : Union[str, Any]=False ,snake_case : Union[str, Any]=False ,snake_case : Optional[int]=1.0 ,snake_case : Optional[Any]=0.2 ,snake_case : Optional[int]=1 ,snake_case : Union[str, Any]=0 ,snake_case : Tuple=2 ,snake_case : List[Any]=False ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size 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 =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE =router_z_loss_coef SCREAMING_SNAKE_CASE =router_aux_loss_coef SCREAMING_SNAKE_CASE =decoder_sparse_step SCREAMING_SNAKE_CASE =encoder_sparse_step SCREAMING_SNAKE_CASE =num_experts SCREAMING_SNAKE_CASE =expert_capacity SCREAMING_SNAKE_CASE =router_bias if router_dtype not in ["float32", "float16", "bfloat16"]: raise ValueError(f'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}' ) SCREAMING_SNAKE_CASE =router_dtype SCREAMING_SNAKE_CASE =router_ignore_padding_tokens SCREAMING_SNAKE_CASE =batch_prioritized_routing SCREAMING_SNAKE_CASE =second_expert_policy SCREAMING_SNAKE_CASE =normalize_router_prob_before_dropping SCREAMING_SNAKE_CASE =moe_eval_capacity_token_fraction SCREAMING_SNAKE_CASE =moe_token_dropout SCREAMING_SNAKE_CASE =output_router_logits super().__init__( pad_token_id=snake_case ,bos_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,**snake_case ,)
334
1
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a_ ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = GPTSanJapaneseTokenizer __UpperCAmelCase = False __UpperCAmelCase = {'do_clean_text': False, 'add_prefix_space': False} def _lowerCAmelCase ( self : List[str] ): super().setUp() # fmt: off SCREAMING_SNAKE_CASE =['こん', 'こんに', 'にちは', 'ばんは', '世界,㔺界', '、', '。', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on SCREAMING_SNAKE_CASE ={'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # 😀 SCREAMING_SNAKE_CASE ={'unk_token': '<unk>'} SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE =os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file ,'w' ) as emoji_writer: emoji_writer.write(json.dumps(snake_case ) ) def _lowerCAmelCase ( self : Dict ,**snake_case : List[str] ): kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname ,**snake_case ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : List[str] ): SCREAMING_SNAKE_CASE ='こんにちは、世界。 \nこんばんは、㔺界。😀' SCREAMING_SNAKE_CASE ='こんにちは、世界。 \nこんばんは、世界。😀' return input_text, output_text def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.get_input_output_texts(snake_case ) SCREAMING_SNAKE_CASE =tokenizer.encode(snake_case ,add_special_tokens=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.decode(snake_case ,clean_up_tokenization_spaces=snake_case ) return text, ids def _lowerCAmelCase ( self : List[Any] ): pass # TODO add if relevant def _lowerCAmelCase ( self : str ): pass # TODO add if relevant def _lowerCAmelCase ( self : Any ): pass # TODO add if relevant def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.get_tokenizer() # Testing tokenization SCREAMING_SNAKE_CASE ='こんにちは、世界。 こんばんは、㔺界。' SCREAMING_SNAKE_CASE =['こん', 'にちは', '、', '世界', '。', '<SP>', 'こん', 'ばんは', '、', '㔺界', '。'] SCREAMING_SNAKE_CASE =tokenizer.tokenize(snake_case ) self.assertListEqual(snake_case ,snake_case ) # Testing conversion to ids without special tokens SCREAMING_SNAKE_CASE =[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] SCREAMING_SNAKE_CASE =tokenizer.convert_tokens_to_ids(snake_case ) self.assertListEqual(snake_case ,snake_case ) # Testing conversion to ids with special tokens SCREAMING_SNAKE_CASE =tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE =[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] SCREAMING_SNAKE_CASE =tokenizer.convert_tokens_to_ids(snake_case ) self.assertListEqual(snake_case ,snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =self.get_tokenizer() # Testing tokenization SCREAMING_SNAKE_CASE ='こんにちは、<|bagoftoken|>世界。こんばんは、<|bagoftoken|>㔺界。' SCREAMING_SNAKE_CASE ='こんにちは、、、、世界。こんばんは、、、、世界。' SCREAMING_SNAKE_CASE =tokenizer.encode(snake_case ) SCREAMING_SNAKE_CASE =tokenizer.decode(snake_case ) self.assertEqual(snake_case ,snake_case ) @slow def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization SCREAMING_SNAKE_CASE ='こんにちは、世界。' SCREAMING_SNAKE_CASE ='こんばんは、㔺界。😀' SCREAMING_SNAKE_CASE ='こんにちは、世界。こんばんは、世界。😀' SCREAMING_SNAKE_CASE =tokenizer.encode(prefix_text + input_text ) SCREAMING_SNAKE_CASE =tokenizer.encode('' ,prefix_text=prefix_text + input_text ) SCREAMING_SNAKE_CASE =tokenizer.encode(snake_case ,prefix_text=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.decode(snake_case ) SCREAMING_SNAKE_CASE =tokenizer.decode(snake_case ) SCREAMING_SNAKE_CASE =tokenizer.decode(snake_case ) self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization SCREAMING_SNAKE_CASE ='こんにちは、世界。' SCREAMING_SNAKE_CASE ='こんばんは、㔺界。😀' SCREAMING_SNAKE_CASE =len(tokenizer.encode(snake_case ) ) - 2 SCREAMING_SNAKE_CASE =len(tokenizer.encode(snake_case ) ) - 2 SCREAMING_SNAKE_CASE =[1] + [0] * (len_prefix + len_text + 1) SCREAMING_SNAKE_CASE =[1] * (len_prefix + len_text + 1) + [0] SCREAMING_SNAKE_CASE =[1] + [1] * (len_prefix) + [0] * (len_text + 1) SCREAMING_SNAKE_CASE =tokenizer(prefix_text + input_text ).token_type_ids SCREAMING_SNAKE_CASE =tokenizer('' ,prefix_text=prefix_text + input_text ).token_type_ids SCREAMING_SNAKE_CASE =tokenizer(snake_case ,prefix_text=snake_case ).token_type_ids self.assertListEqual(snake_case ,snake_case ) self.assertListEqual(snake_case ,snake_case ) self.assertListEqual(snake_case ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) SCREAMING_SNAKE_CASE =tokenizer.encode('あンいワ' ) SCREAMING_SNAKE_CASE =tokenizer.encode('' ,prefix_text='あンいワ' ) SCREAMING_SNAKE_CASE =tokenizer.encode('いワ' ,prefix_text='あン' ) self.assertEqual(tokenizer.decode(snake_case ) ,tokenizer.decode(snake_case ) ) self.assertEqual(tokenizer.decode(snake_case ) ,tokenizer.decode(snake_case ) ) self.assertNotEqual(snake_case ,snake_case ) self.assertNotEqual(snake_case ,snake_case ) self.assertEqual(x_token_a[1] ,x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] ,x_token_a[3] ) # SEG token @slow def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) SCREAMING_SNAKE_CASE =[['武田信玄', 'は、'], ['織田信長', 'の配下の、']] SCREAMING_SNAKE_CASE =tokenizer(snake_case ,padding=snake_case ) SCREAMING_SNAKE_CASE =tokenizer.batch_encode_plus(snake_case ,padding=snake_case ) # fmt: off SCREAMING_SNAKE_CASE =[[35993, 8640, 25948, 35998, 30647, 35675, 35999, 35999], [35993, 10382, 9868, 35998, 30646, 9459, 30646, 35675]] SCREAMING_SNAKE_CASE =[[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] SCREAMING_SNAKE_CASE =[[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids ,snake_case ) self.assertListEqual(x_token.token_type_ids ,snake_case ) self.assertListEqual(x_token.attention_mask ,snake_case ) self.assertListEqual(x_token_a.input_ids ,snake_case ) self.assertListEqual(x_token_a.token_type_ids ,snake_case ) self.assertListEqual(x_token_a.attention_mask ,snake_case ) def _lowerCAmelCase ( self : List[Any] ): # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def _lowerCAmelCase ( self : Tuple ): # tokenizer has no padding token pass
334
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =sorted(numsa + numsa ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =divmod(len(lowerCAmelCase_ ), 2 ) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase =[float(x) for x in input("Enter the elements of first array: ").split()] _lowerCamelCase =[float(x) for x in input("Enter the elements of second array: ").split()] print(f'The median of two arrays is: {median_of_two_arrays(array_a, array_a)}')
334
1
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 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 =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_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.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , 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 a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : 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(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : 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(snake_case ) 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] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'transfo-xl' __UpperCAmelCase = ['mems'] __UpperCAmelCase = { 'n_token': 'vocab_size', 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Union[str, Any] ,snake_case : List[Any]=267735 ,snake_case : Optional[int]=[20000, 40000, 200000] ,snake_case : int=1024 ,snake_case : Optional[Any]=1024 ,snake_case : Tuple=16 ,snake_case : int=64 ,snake_case : Union[str, Any]=4096 ,snake_case : List[str]=4 ,snake_case : int=False ,snake_case : int=18 ,snake_case : Tuple=1600 ,snake_case : List[str]=1000 ,snake_case : Optional[Any]=True ,snake_case : List[str]=True ,snake_case : Optional[Any]=0 ,snake_case : Optional[Any]=-1 ,snake_case : List[Any]=True ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : int=True ,snake_case : Any="normal" ,snake_case : int=0.01 ,snake_case : int=0.01 ,snake_case : str=0.02 ,snake_case : Any=1e-5 ,snake_case : Optional[int]=0 ,**snake_case : List[Any] ,): SCREAMING_SNAKE_CASE =vocab_size SCREAMING_SNAKE_CASE =[] self.cutoffs.extend(snake_case ) if proj_share_all_but_first: SCREAMING_SNAKE_CASE =[False] + [True] * len(self.cutoffs ) else: SCREAMING_SNAKE_CASE =[False] + [False] * len(self.cutoffs ) SCREAMING_SNAKE_CASE =d_model SCREAMING_SNAKE_CASE =d_embed SCREAMING_SNAKE_CASE =d_head SCREAMING_SNAKE_CASE =d_inner SCREAMING_SNAKE_CASE =div_val SCREAMING_SNAKE_CASE =pre_lnorm SCREAMING_SNAKE_CASE =n_layer SCREAMING_SNAKE_CASE =n_head SCREAMING_SNAKE_CASE =mem_len SCREAMING_SNAKE_CASE =same_length SCREAMING_SNAKE_CASE =attn_type SCREAMING_SNAKE_CASE =clamp_len SCREAMING_SNAKE_CASE =sample_softmax SCREAMING_SNAKE_CASE =adaptive SCREAMING_SNAKE_CASE =dropout SCREAMING_SNAKE_CASE =dropatt SCREAMING_SNAKE_CASE =untie_r SCREAMING_SNAKE_CASE =init SCREAMING_SNAKE_CASE =init_range SCREAMING_SNAKE_CASE =proj_init_std SCREAMING_SNAKE_CASE =init_std SCREAMING_SNAKE_CASE =layer_norm_epsilon super().__init__(eos_token_id=snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : str ): # Message copied from Transformer-XL documentation logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Dict ): # Message copied from Transformer-XL documentation raise NotImplementedError( f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
334
1
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class a_ : """simple docstring""" def __init__( self : Optional[int] ,snake_case : Any ,snake_case : Dict=100 ,snake_case : List[Any]=13 ,snake_case : str=30 ,snake_case : List[str]=2 ,snake_case : List[Any]=3 ,snake_case : Tuple=True ,snake_case : Optional[Any]=True ,snake_case : int=32 ,snake_case : Tuple=4 ,snake_case : List[Any]=4 ,snake_case : Optional[Any]=37 ,snake_case : Optional[Any]="gelu" ,snake_case : Tuple=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : List[Any]=10 ,snake_case : Tuple=0.02 ,snake_case : List[str]=3 ,snake_case : Any=None ,snake_case : int=[0, 1, 2, 3] ,): SCREAMING_SNAKE_CASE =parent SCREAMING_SNAKE_CASE =100 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 =scope SCREAMING_SNAKE_CASE =out_indices SCREAMING_SNAKE_CASE =num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE =(image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE =num_patches + 1 def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_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.image_size, self.image_size] ,self.num_labels ) SCREAMING_SNAKE_CASE =self.get_config() return config, pixel_values, labels, pixel_labels def _lowerCAmelCase ( self : Dict ): return BeitConfig( vocab_size=self.vocab_size ,image_size=self.image_size ,patch_size=self.patch_size ,num_channels=self.num_channels ,hidden_size=self.hidden_size ,num_hidden_layers=self.num_hidden_layers ,num_attention_heads=self.num_attention_heads ,intermediate_size=self.intermediate_size ,hidden_act=self.hidden_act ,hidden_dropout_prob=self.hidden_dropout_prob ,attention_probs_dropout_prob=self.attention_probs_dropout_prob ,is_decoder=snake_case ,initializer_range=self.initializer_range ,out_indices=self.out_indices ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Tuple ,snake_case : Optional[Any] ,snake_case : Union[str, Any] ,snake_case : Optional[int] ): SCREAMING_SNAKE_CASE =BeitModel(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : Dict ,snake_case : Any ,snake_case : List[str] ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling(config=snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length - 1, self.vocab_size) ) def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Any ,snake_case : str ,snake_case : Any ,snake_case : str ): SCREAMING_SNAKE_CASE =self.type_sequence_label_size SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE =1 SCREAMING_SNAKE_CASE =BeitForImageClassification(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.type_sequence_label_size) ) def _lowerCAmelCase ( self : List[str] ,snake_case : Tuple ,snake_case : str ,snake_case : Optional[int] ,snake_case : int ): SCREAMING_SNAKE_CASE =self.num_labels SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation(snake_case ) model.to(snake_case ) model.eval() SCREAMING_SNAKE_CASE =model(snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE =model(snake_case ,labels=snake_case ) self.parent.assertEqual( result.logits.shape ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _lowerCAmelCase ( self : str ): SCREAMING_SNAKE_CASE =self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , 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 a_ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __UpperCAmelCase = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def _lowerCAmelCase ( self : List[Any] ): SCREAMING_SNAKE_CASE =BeitModelTester(self ) SCREAMING_SNAKE_CASE =ConfigTester(self ,config_class=snake_case ,has_text_modality=snake_case ,hidden_size=37 ) def _lowerCAmelCase ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def _lowerCAmelCase ( self : List[Any] ): pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def _lowerCAmelCase ( self : Union[str, Any] ): pass def _lowerCAmelCase ( self : 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(snake_case ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) SCREAMING_SNAKE_CASE =model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case ,nn.Linear ) ) def _lowerCAmelCase ( self : 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(snake_case ) 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] ,snake_case ) def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case ) def _lowerCAmelCase ( self : Dict ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*snake_case ) def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*snake_case ) def _lowerCAmelCase ( self : Any ): if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(snake_case ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE =False SCREAMING_SNAKE_CASE =True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(snake_case ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE =model_class(snake_case ) model.gradient_checkpointing_enable() model.to(snake_case ) model.train() SCREAMING_SNAKE_CASE =self._prepare_for_class(snake_case ,snake_case ,return_labels=snake_case ) SCREAMING_SNAKE_CASE =model(**snake_case ).loss loss.backward() def _lowerCAmelCase ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE =_config_zero_init(snake_case ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE =model_class(config=snake_case ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() ,[0.0, 1.0] ,msg=f'Parameter {name} of model {model_class} seems not properly initialized' ,) @slow def _lowerCAmelCase ( self : List[str] ): for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE =BeitModel.from_pretrained(snake_case ) self.assertIsNotNone(snake_case ) def snake_case__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): """simple docstring""" @cached_property def _lowerCAmelCase ( self : Tuple ): return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).pixel_values.to(snake_case ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE =torch.ones((1, 196) ,dtype=torch.bool ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(pixel_values=snake_case ,bool_masked_pos=snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(snake_case ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] ,snake_case ,atol=1e-2 ) ) @slow def _lowerCAmelCase ( self : List[str] ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 1000) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =281 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( snake_case ) SCREAMING_SNAKE_CASE =self.default_image_processor SCREAMING_SNAKE_CASE =prepare_img() SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 21841) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(snake_case ) self.assertTrue(torch.allclose(logits[0, :3] ,snake_case ,atol=1e-4 ) ) SCREAMING_SNAKE_CASE =2396 self.assertEqual(logits.argmax(-1 ).item() ,snake_case ) @slow def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits # verify the logits SCREAMING_SNAKE_CASE =torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape ,snake_case ) SCREAMING_SNAKE_CASE =version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] ,device=snake_case ,) else: SCREAMING_SNAKE_CASE =torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] ,device=snake_case ,) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,snake_case ,atol=1e-4 ) ) @slow def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE =model.to(snake_case ) SCREAMING_SNAKE_CASE =BeitImageProcessor(do_resize=snake_case ,size=640 ,do_center_crop=snake_case ) SCREAMING_SNAKE_CASE =load_dataset('hf-internal-testing/fixtures_ade20k' ,split='test' ) SCREAMING_SNAKE_CASE =Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE =image_processor(images=snake_case ,return_tensors='pt' ).to(snake_case ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE =model(**snake_case ) SCREAMING_SNAKE_CASE =outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ,target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE =torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape ,snake_case ) SCREAMING_SNAKE_CASE =image_processor.post_process_semantic_segmentation(outputs=snake_case ) SCREAMING_SNAKE_CASE =torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape ,snake_case )
334
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase ={ "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimesformerModel", "TimesformerForVideoClassification", "TimesformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase =logging.get_logger() @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) def _lowerCAmelCase ( self : List[Any] ,snake_case : Dict ,snake_case : Tensor ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =len(list(m.modules() ) ) == 1 or isinstance(snake_case ,nn.Convad ) or isinstance(snake_case ,nn.BatchNormad ) if has_not_submodules: self.traced.append(snake_case ) def __call__( self : List[str] ,snake_case : Tensor ): for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(snake_case ) [x.remove() for x in self.handles] return self @property def _lowerCAmelCase ( self : Optional[Any] ): # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda snake_case : len(list(x.state_dict().keys() ) ) > 0 ,self.traced ) ) @dataclass class a_ : """simple docstring""" __UpperCAmelCase = 42 __UpperCAmelCase = 42 __UpperCAmelCase = 1 __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = field(default_factory=lowerCamelCase_ ) __UpperCAmelCase = True def __call__( self : str ,snake_case : Tensor ): SCREAMING_SNAKE_CASE =Tracker(self.dest )(snake_case ).parametrized SCREAMING_SNAKE_CASE =Tracker(self.src )(snake_case ).parametrized SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.src_skip ,snake_case ) ) SCREAMING_SNAKE_CASE =list(filter(lambda snake_case : type(snake_case ) not in self.dest_skip ,snake_case ) ) if len(snake_case ) != len(snake_case ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(snake_case )} operations while' f' destination module has {len(snake_case )}.' ) for dest_m, src_m in zip(snake_case ,snake_case ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): """simple docstring""" def __init__( self : Any ,snake_case : nn.Module ): super().__init__() SCREAMING_SNAKE_CASE =[] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), f'Unexpected layer name {k}' SCREAMING_SNAKE_CASE =len(snake_case ) + 1 feature_blocks.append((f'res{block_index}', v) ) SCREAMING_SNAKE_CASE =nn.ModuleDict(snake_case ) def _lowerCAmelCase ( self : Dict ,snake_case : Tensor ): return get_trunk_forward_outputs( snake_case ,out_feat_keys=snake_case ,feature_blocks=self._feature_blocks ,) class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[int] ,snake_case : str ): SCREAMING_SNAKE_CASE =x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[Any] ,snake_case : str ): # default to timm! if x not in self: SCREAMING_SNAKE_CASE =self.convert_name_to_timm(snake_case ) SCREAMING_SNAKE_CASE =partial(lambda: (timm.create_model(snake_case ,pretrained=snake_case ).eval(), None) ) else: SCREAMING_SNAKE_CASE =super().__getitem__(snake_case ) return val class a_ ( lowerCamelCase_ ): """simple docstring""" def __getitem__( self : int ,snake_case : str ): if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE =RegNetModel else: SCREAMING_SNAKE_CASE =RegNetForImageClassification return val def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" for from_key, to_key in keys: SCREAMING_SNAKE_CASE =from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ = True, ): """simple docstring""" print(F'Converting {name}...' ) with torch.no_grad(): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =from_model_func() SCREAMING_SNAKE_CASE =our_model_func(lowerCAmelCase_ ).eval() SCREAMING_SNAKE_CASE =ModuleTransfer(src=lowerCAmelCase_, dest=lowerCAmelCase_, raise_if_mismatch=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE =[] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =[('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE =manually_copy_vissl_head(lowerCAmelCase_, our_model.state_dict(), lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =our_model(lowerCAmelCase_, output_hidden_states=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =( our_outputs.logits if isinstance(lowerCAmelCase_, lowerCAmelCase_ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE =from_model(lowerCAmelCase_ ) SCREAMING_SNAKE_CASE =from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE =our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_, lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add model', use_temp_dir=lowerCAmelCase_, ) SCREAMING_SNAKE_CASE =224 if 'seer' not in name else 384 # we can use the convnext one SCREAMING_SNAKE_CASE =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k', size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name, commit_message='Add image processor', use_temp_dir=lowerCAmelCase_, ) print(F'Pushed {name}' ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_ = None, lowerCAmelCase_ = True ): """simple docstring""" SCREAMING_SNAKE_CASE ='imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE =1000 SCREAMING_SNAKE_CASE =(1, num_labels) SCREAMING_SNAKE_CASE ='huggingface/label-files' SCREAMING_SNAKE_CASE =num_labels SCREAMING_SNAKE_CASE =json.load(open(cached_download(hf_hub_url(lowerCAmelCase_, lowerCAmelCase_, repo_type='dataset' ) ), 'r' ) ) SCREAMING_SNAKE_CASE ={int(lowerCAmelCase_ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =idalabel SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE =partial(lowerCAmelCase_, num_labels=lowerCAmelCase_, idalabel=lowerCAmelCase_, labelaid=lowerCAmelCase_ ) SCREAMING_SNAKE_CASE ={ 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8, layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12], hidden_sizes=[32, 64, 160, 384], groups_width=16, layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7], hidden_sizes=[48, 96, 240, 528], groups_width=24, layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5], hidden_sizes=[64, 128, 288, 672], groups_width=16, layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2], hidden_sizes=[72, 168, 408, 912], groups_width=24, layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2], hidden_sizes=[96, 192, 432, 1008], groups_width=48, layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2], hidden_sizes=[80, 240, 560, 1360], groups_width=40, layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 392, 784, 1624], groups_width=56, layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1], hidden_sizes=[80, 240, 720, 1920], groups_width=120, layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112, layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1], hidden_sizes=[256, 512, 896, 2048], groups_width=128, layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1], hidden_sizes=[336, 672, 1344, 2520], groups_width=168, layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7], hidden_sizes=[24, 56, 152, 368], groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6], hidden_sizes=[48, 104, 208, 440], groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4], hidden_sizes=[48, 112, 256, 608], groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2], hidden_sizes=[64, 128, 320, 768], groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2], hidden_sizes=[48, 120, 336, 888], groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1], hidden_sizes=[72, 216, 576, 1512], groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2], hidden_sizes=[128, 192, 512, 1088], groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2], hidden_sizes=[144, 288, 576, 1296], groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1], hidden_sizes=[168, 448, 896, 2016], groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1], hidden_sizes=[224, 448, 896, 2240], groups_width=112 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1], hidden_sizes=[224, 448, 1232, 3024], groups_width=112 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[232, 696, 1392, 3712], groups_width=232 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1], hidden_sizes=[328, 984, 1968, 4920], groups_width=328 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[528, 1056, 2904, 7392], groups_width=264 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1], hidden_sizes=[640, 1696, 2544, 5088], groups_width=640 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1], hidden_sizes=[2020, 4040, 11110, 28280], groups_width=1010 ), } SCREAMING_SNAKE_CASE =NameToOurModelFuncMap() SCREAMING_SNAKE_CASE =NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_, lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE =torch.hub.load_state_dict_from_url(lowerCAmelCase_, model_dir=str(lowerCAmelCase_ ), map_location='cpu' ) SCREAMING_SNAKE_CASE =model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE =files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE =model_state_dict['trunk'] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) # IN1K finetuned SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch', lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ), ) SCREAMING_SNAKE_CASE =partial( lowerCAmelCase_, 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch', lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27, group_width=1010, w_a=1744, w_a=620.83, w_m=2.52 ) ) ), ) if model_name: convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], names_to_config[model_name], lowerCAmelCase_, lowerCAmelCase_, ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_, names_to_from_model_map[model_name], names_to_ours_model_map[model_name], lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ) return config, expected_shape if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) _lowerCamelCase =parser.parse_args() _lowerCamelCase =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
334
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "google/pegasus-large": "https://huggingface.co/google/pegasus-large/resolve/main/config.json", # See all PEGASUS models at https://huggingface.co/models?filter=pegasus } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'pegasus' __UpperCAmelCase = ['past_key_values'] __UpperCAmelCase = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : str ,snake_case : List[str]=50265 ,snake_case : Optional[Any]=1024 ,snake_case : str=12 ,snake_case : List[Any]=4096 ,snake_case : Optional[Any]=16 ,snake_case : List[Any]=12 ,snake_case : Tuple=4096 ,snake_case : int=16 ,snake_case : Any=0.0 ,snake_case : Any=0.0 ,snake_case : str=True ,snake_case : Tuple=True ,snake_case : Union[str, Any]="gelu" ,snake_case : List[str]=1024 ,snake_case : Any=0.1 ,snake_case : Union[str, Any]=0.0 ,snake_case : Union[str, Any]=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : List[Any]=0 ,snake_case : Optional[Any]=False ,snake_case : Any=0 ,snake_case : Tuple=1 ,snake_case : List[Any]=1 ,**snake_case : Tuple ,): SCREAMING_SNAKE_CASE =vocab_size 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 =encoder_layerdrop SCREAMING_SNAKE_CASE =decoder_layerdrop SCREAMING_SNAKE_CASE =use_cache SCREAMING_SNAKE_CASE =encoder_layers SCREAMING_SNAKE_CASE =scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=snake_case ,eos_token_id=snake_case ,is_encoder_decoder=snake_case ,decoder_start_token_id=snake_case ,forced_eos_token_id=snake_case ,**snake_case ,) @property def _lowerCAmelCase ( self : List[str] ): return self.encoder_attention_heads @property def _lowerCAmelCase ( self : str ): return self.d_model
334
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 # ######################################################################## _lowerCamelCase =16 _lowerCamelCase =32 def snake_case__ ( 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 _lowerCamelCase =mocked_dataloaders # noqa: F811 def snake_case__ ( 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 snake_case__ ( ): """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()
334
1
from __future__ import annotations def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_ ): """simple docstring""" if days_between_payments <= 0: raise ValueError('days_between_payments must be > 0' ) if daily_interest_rate < 0: raise ValueError('daily_interest_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * daily_interest_rate * days_between_payments def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" if number_of_compounding_periods <= 0: raise ValueError('number_of_compounding_periods must be > 0' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def snake_case__ ( lowerCAmelCase_, lowerCAmelCase_, lowerCAmelCase_, ): """simple docstring""" if number_of_years <= 0: raise ValueError('number_of_years must be > 0' ) if nominal_annual_percentage_rate < 0: raise ValueError('nominal_annual_percentage_rate must be >= 0' ) if principal <= 0: raise ValueError('principal must be > 0' ) return compound_interest( lowerCAmelCase_, nominal_annual_percentage_rate / 365, number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
334
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" return " ".join( ''.join(word[::-1] ) if len(lowerCAmelCase_ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words("Hey wollef sroirraw"))
334
1
def snake_case__ ( lowerCAmelCase_ ): """simple docstring""" SCREAMING_SNAKE_CASE =False while is_sorted is False: # Until all the indices are traversed keep looping SCREAMING_SNAKE_CASE =True for i in range(0, len(lowerCAmelCase_ ) - 1, 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE =False for i in range(1, len(lowerCAmelCase_ ) - 1, 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =input_list[i + 1], input_list[i] # swapping if elements not in order SCREAMING_SNAKE_CASE =False return input_list if __name__ == "__main__": print("Enter list to be sorted") _lowerCamelCase =[int(x) for x in input().split()] # inputing elements of the list in one line _lowerCamelCase =odd_even_sort(input_list) print("The sorted list is") print(sorted_list)
334
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _lowerCamelCase ="sshleifer/mar_enro_6_3_student" class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE =cached_path( 'https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz' ,extract_compressed_file=snake_case ,) SCREAMING_SNAKE_CASE =f'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[int] ): MarianMTModel.from_pretrained(snake_case ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Tuple ): SCREAMING_SNAKE_CASE ={ '$MAX_LEN': 64, '$BS': 64, '$GAS': 1, '$ENRO_DIR': self.data_dir, 'facebook/mbart-large-cc25': MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", '--learning_rate=3e-5': '--learning_rate 3e-4', '--num_train_epochs 6': '--num_train_epochs 1', } # Clean up bash script SCREAMING_SNAKE_CASE =(self.test_file_dir / 'train_mbart_cc25_enro.sh').open().read().split('finetune.py' )[1].strip() SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") SCREAMING_SNAKE_CASE =f'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future SCREAMING_SNAKE_CASE =['finetune.py'] + bash_script.split() + args with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationModule.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() SCREAMING_SNAKE_CASE =main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] self.assertEqual(len(metrics['val'] ) ,(args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) self.assertGreater(last_step_stats['val_avg_gen_time'] ,0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats['val_avg_gen_time'] ,1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats['val_avg_bleu'] - first_step_stats['val_avg_bleu'] ,2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats['val_avg_bleu'] ,17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics['val'][-1]['val_avg_bleu'] - metrics['test'][-1]['test_avg_bleu'] ) ,1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1 class a_ ( lowerCamelCase_ ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =f'{self.test_file_dir_str}/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE ={ '--fp16_opt_level=O1': '', '$MAX_LEN': 128, '$BS': 16, '$GAS': 1, '$ENRO_DIR': data_dir, '$m': 'sshleifer/student_marian_en_ro_6_1', 'val_check_interval=0.25': 'val_check_interval=1.0', } # Clean up bash script SCREAMING_SNAKE_CASE =( (self.test_file_dir / 'distil_marian_no_teacher.sh').open().read().split('distillation.py' )[1].strip() ) SCREAMING_SNAKE_CASE =bash_script.replace('\\\n' ,'' ).strip().replace('"$@"' ,'' ) SCREAMING_SNAKE_CASE =bash_script.replace('--fp16 ' ,' ' ) for k, v in env_vars_to_replace.items(): SCREAMING_SNAKE_CASE =bash_script.replace(snake_case ,str(snake_case ) ) SCREAMING_SNAKE_CASE =self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE =bash_script.replace('--fp16' ,'' ) SCREAMING_SNAKE_CASE =6 SCREAMING_SNAKE_CASE =( ['distillation.py'] + bash_script.split() + [ f'--output_dir={output_dir}', '--gpus=1', '--learning_rate=1e-3', f'--num_train_epochs={epochs}', '--warmup_steps=10', '--val_check_interval=1.0', '--do_predict', ] ) with patch.object(snake_case ,'argv' ,snake_case ): SCREAMING_SNAKE_CASE =argparse.ArgumentParser() SCREAMING_SNAKE_CASE =pl.Trainer.add_argparse_args(snake_case ) SCREAMING_SNAKE_CASE =SummarizationDistiller.add_model_specific_args(snake_case ,os.getcwd() ) SCREAMING_SNAKE_CASE =parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu SCREAMING_SNAKE_CASE =distill_main(snake_case ) # Check metrics SCREAMING_SNAKE_CASE =load_json(model.metrics_save_path ) SCREAMING_SNAKE_CASE =metrics['val'][0] SCREAMING_SNAKE_CASE =metrics['val'][-1] assert len(metrics['val'] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f'val_avg_{model.val_metric}'] ,snake_case ) # check lightning ckpt can be loaded and has a reasonable statedict SCREAMING_SNAKE_CASE =os.listdir(snake_case ) SCREAMING_SNAKE_CASE =[x for x in contents if x.endswith('.ckpt' )][0] SCREAMING_SNAKE_CASE =os.path.join(args.output_dir ,snake_case ) SCREAMING_SNAKE_CASE =torch.load(snake_case ,map_location='cpu' ) SCREAMING_SNAKE_CASE ='model.model.decoder.layers.0.encoder_attn_layer_norm.weight' assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: SCREAMING_SNAKE_CASE ={os.path.basename(snake_case ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics['test'] ) == 1
334
1
from tempfile import TemporaryDirectory from unittest import TestCase from unittest.mock import MagicMock, patch from transformers import AutoModel, TFAutoModel from transformers.onnx import FeaturesManager from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch @require_torch @require_tf class a_ ( lowerCamelCase_ ): """simple docstring""" def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =SMALL_MODEL_IDENTIFIER SCREAMING_SNAKE_CASE ='pt' SCREAMING_SNAKE_CASE ='tf' def _lowerCAmelCase ( self : Optional[Any] ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =AutoModel.from_pretrained(self.test_model ) model_pt.save_pretrained(snake_case ) def _lowerCAmelCase ( self : Optional[int] ,snake_case : Tuple ): SCREAMING_SNAKE_CASE =TFAutoModel.from_pretrained(self.test_model ,from_pt=snake_case ) model_tf.save_pretrained(snake_case ) def _lowerCAmelCase ( self : Optional[int] ): SCREAMING_SNAKE_CASE ='mock_framework' # Framework provided - return whatever the user provides SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(self.test_model ,snake_case ) self.assertEqual(snake_case ,snake_case ) # Local checkpoint and framework provided - return provided framework # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(snake_case ) SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(snake_case ) SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(snake_case ,snake_case ) self.assertEqual(snake_case ,snake_case ) def _lowerCAmelCase ( self : Tuple ): # PyTorch checkpoint with TemporaryDirectory() as local_pt_ckpt: self._setup_pt_ckpt(snake_case ) SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(snake_case ) self.assertEqual(snake_case ,self.framework_pt ) # TensorFlow checkpoint with TemporaryDirectory() as local_tf_ckpt: self._setup_tf_ckpt(snake_case ) SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(snake_case ) self.assertEqual(snake_case ,self.framework_tf ) # Invalid local checkpoint with TemporaryDirectory() as local_invalid_ckpt: with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(snake_case ) def _lowerCAmelCase ( self : int ): SCREAMING_SNAKE_CASE =MagicMock(return_value=snake_case ) with patch('transformers.onnx.features.is_tf_available' ,snake_case ): SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case ,self.framework_pt ) # PyTorch not in environment -> use TensorFlow SCREAMING_SNAKE_CASE =MagicMock(return_value=snake_case ) with patch('transformers.onnx.features.is_torch_available' ,snake_case ): SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case ,self.framework_tf ) # Both in environment -> use PyTorch SCREAMING_SNAKE_CASE =MagicMock(return_value=snake_case ) SCREAMING_SNAKE_CASE =MagicMock(return_value=snake_case ) with patch('transformers.onnx.features.is_tf_available' ,snake_case ), patch( 'transformers.onnx.features.is_torch_available' ,snake_case ): SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(self.test_model ) self.assertEqual(snake_case ,self.framework_pt ) # Both not in environment -> raise error SCREAMING_SNAKE_CASE =MagicMock(return_value=snake_case ) SCREAMING_SNAKE_CASE =MagicMock(return_value=snake_case ) with patch('transformers.onnx.features.is_tf_available' ,snake_case ), patch( 'transformers.onnx.features.is_torch_available' ,snake_case ): with self.assertRaises(snake_case ): SCREAMING_SNAKE_CASE =FeaturesManager.determine_framework(self.test_model )
334
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json", } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_vision_model' def __init__( self : List[Any] ,snake_case : List[Any]=1408 ,snake_case : Optional[Any]=6144 ,snake_case : Optional[int]=39 ,snake_case : Optional[int]=16 ,snake_case : Optional[Any]=224 ,snake_case : Tuple=14 ,snake_case : Optional[Any]="gelu" ,snake_case : Union[str, Any]=0.00_001 ,snake_case : Dict=0.0 ,snake_case : Union[str, Any]=1e-10 ,snake_case : int=True ,**snake_case : str ,): super().__init__(**snake_case ) SCREAMING_SNAKE_CASE =hidden_size SCREAMING_SNAKE_CASE =intermediate_size 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 SCREAMING_SNAKE_CASE =qkv_bias @classmethod def _lowerCAmelCase ( cls : Dict ,snake_case : Union[str, os.PathLike] ,**snake_case : str ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": 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(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip_2_qformer' def __init__( self : Any ,snake_case : Dict=30522 ,snake_case : int=768 ,snake_case : List[Any]=12 ,snake_case : List[str]=12 ,snake_case : Optional[Any]=3072 ,snake_case : str="gelu" ,snake_case : Optional[Any]=0.1 ,snake_case : Union[str, Any]=0.1 ,snake_case : Optional[Any]=512 ,snake_case : List[Any]=0.02 ,snake_case : List[str]=1e-12 ,snake_case : Tuple=0 ,snake_case : Union[str, Any]="absolute" ,snake_case : List[Any]=2 ,snake_case : List[str]=1408 ,**snake_case : Optional[Any] ,): super().__init__(pad_token_id=snake_case ,**snake_case ) 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 =initializer_range SCREAMING_SNAKE_CASE =layer_norm_eps SCREAMING_SNAKE_CASE =position_embedding_type SCREAMING_SNAKE_CASE =cross_attention_frequency SCREAMING_SNAKE_CASE =encoder_hidden_size @classmethod def _lowerCAmelCase ( cls : List[Any] ,snake_case : Union[str, os.PathLike] ,**snake_case : Dict ): cls._set_token_in_kwargs(snake_case ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE =cls.get_config_dict(snake_case ,**snake_case ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('model_type' ) == "blip-2": SCREAMING_SNAKE_CASE =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls ,'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' f'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case ,**snake_case ) class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'blip-2' __UpperCAmelCase = True def __init__( self : int ,snake_case : Dict=None ,snake_case : Tuple=None ,snake_case : str=None ,snake_case : Union[str, Any]=32 ,**snake_case : int ): super().__init__(**snake_case ) if vision_config is None: SCREAMING_SNAKE_CASE ={} logger.info('vision_config is None. initializing the Blip2VisionConfig with default values.' ) if qformer_config is None: SCREAMING_SNAKE_CASE ={} logger.info('qformer_config is None. Initializing the Blip2QFormerConfig with default values.' ) if text_config is None: SCREAMING_SNAKE_CASE ={} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) SCREAMING_SNAKE_CASE =BlipaVisionConfig(**snake_case ) SCREAMING_SNAKE_CASE =BlipaQFormerConfig(**snake_case ) SCREAMING_SNAKE_CASE =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE =CONFIG_MAPPING[text_model_type](**snake_case ) SCREAMING_SNAKE_CASE =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE =num_query_tokens SCREAMING_SNAKE_CASE =self.vision_config.hidden_size SCREAMING_SNAKE_CASE =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE =1.0 SCREAMING_SNAKE_CASE =0.02 @classmethod def _lowerCAmelCase ( cls : Union[str, Any] ,snake_case : BlipaVisionConfig ,snake_case : BlipaQFormerConfig ,snake_case : PretrainedConfig ,**snake_case : Any ,): return cls( vision_config=vision_config.to_dict() ,qformer_config=qformer_config.to_dict() ,text_config=text_config.to_dict() ,**snake_case ,) def _lowerCAmelCase ( self : Optional[Any] ): SCREAMING_SNAKE_CASE =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE =self.vision_config.to_dict() SCREAMING_SNAKE_CASE =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE =self.text_config.to_dict() SCREAMING_SNAKE_CASE =self.__class__.model_type return output
334
1
from typing import TYPE_CHECKING from ...utils import _LazyModule _lowerCamelCase ={"processing_wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"]} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _lowerCamelCase ="\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _lowerCamelCase ="\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _lowerCamelCase ="\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): """simple docstring""" def _lowerCAmelCase ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,homepage='https://github.com/krishnap25/mauve' ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { 'predictions': datasets.Value('string' ,id='sequence' ), 'references': datasets.Value('string' ,id='sequence' ), } ) ,codebase_urls=['https://github.com/krishnap25/mauve'] ,reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] ,) def _lowerCAmelCase ( self : Union[str, Any] ,snake_case : Optional[int] ,snake_case : str ,snake_case : List[str]=None ,snake_case : str=None ,snake_case : int=None ,snake_case : Union[str, Any]=None ,snake_case : Optional[int]="auto" ,snake_case : List[str]=-1 ,snake_case : Union[str, Any]=0.9 ,snake_case : Tuple=5 ,snake_case : Union[str, Any]=500 ,snake_case : Union[str, Any]="gpt2-large" ,snake_case : Union[str, Any]=-1 ,snake_case : Optional[Any]=1024 ,snake_case : Optional[Any]=25 ,snake_case : List[str]=5 ,snake_case : List[str]=True ,snake_case : Optional[Any]=25 ,): SCREAMING_SNAKE_CASE =compute_mauve( p_text=snake_case ,q_text=snake_case ,p_features=snake_case ,q_features=snake_case ,p_tokens=snake_case ,q_tokens=snake_case ,num_buckets=snake_case ,pca_max_data=snake_case ,kmeans_explained_var=snake_case ,kmeans_num_redo=snake_case ,kmeans_max_iter=snake_case ,featurize_model_name=snake_case ,device_id=snake_case ,max_text_length=snake_case ,divergence_curve_discretization_size=snake_case ,mauve_scaling_factor=snake_case ,verbose=snake_case ,seed=snake_case ,) return out
334
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = ['image_processor', 'tokenizer'] __UpperCAmelCase = 'ViTImageProcessor' __UpperCAmelCase = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] ,snake_case : List[str]=None ,snake_case : Optional[int]=None ,**snake_case : Dict ): SCREAMING_SNAKE_CASE =None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' ,snake_case ,) SCREAMING_SNAKE_CASE =kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE =image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(snake_case ,snake_case ) def __call__( self : Union[str, Any] ,snake_case : List[Any]=None ,snake_case : Any=None ,snake_case : Optional[int]=None ,snake_case : Union[str, Any]=None ,**snake_case : Any ): if text is None and visual_prompt is None and images is None: raise ValueError('You have to specify either text, visual prompt or images.' ) if text is not None and visual_prompt is not None: raise ValueError('You have to specify exactly one type of prompt. Either text or visual prompt.' ) if text is not None: SCREAMING_SNAKE_CASE =self.tokenizer(snake_case ,return_tensors=snake_case ,**snake_case ) if visual_prompt is not None: SCREAMING_SNAKE_CASE =self.image_processor(snake_case ,return_tensors=snake_case ,**snake_case ) if images is not None: SCREAMING_SNAKE_CASE =self.image_processor(snake_case ,return_tensors=snake_case ,**snake_case ) if visual_prompt is not None and images is not None: SCREAMING_SNAKE_CASE ={ 'pixel_values': image_features.pixel_values, 'conditional_pixel_values': prompt_features.pixel_values, } return encoding elif text is not None and images is not None: SCREAMING_SNAKE_CASE =image_features.pixel_values return encoding elif text is not None: return encoding elif visual_prompt is not None: SCREAMING_SNAKE_CASE ={ 'conditional_pixel_values': prompt_features.pixel_values, } return encoding else: return BatchEncoding(data=dict(**snake_case ) ,tensor_type=snake_case ) def _lowerCAmelCase ( self : Dict ,*snake_case : List[str] ,**snake_case : Optional[Any] ): return self.tokenizer.batch_decode(*snake_case ,**snake_case ) def _lowerCAmelCase ( self : int ,*snake_case : Union[str, Any] ,**snake_case : List[str] ): return self.tokenizer.decode(*snake_case ,**snake_case ) @property def _lowerCAmelCase ( self : Tuple ): warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' ,snake_case ,) return self.image_processor_class @property def _lowerCAmelCase ( self : Dict ): warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' ,snake_case ,) return self.image_processor
334
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ "facebook/vit-mae-base": "https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json", # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class a_ ( lowerCamelCase_ ): """simple docstring""" __UpperCAmelCase = 'vit_mae' def __init__( self : Union[str, Any] ,snake_case : Any=768 ,snake_case : List[str]=12 ,snake_case : Optional[int]=12 ,snake_case : int=3072 ,snake_case : List[Any]="gelu" ,snake_case : str=0.0 ,snake_case : str=0.0 ,snake_case : Optional[Any]=0.02 ,snake_case : Dict=1e-12 ,snake_case : List[str]=224 ,snake_case : Any=16 ,snake_case : Any=3 ,snake_case : Tuple=True ,snake_case : List[Any]=16 ,snake_case : List[str]=512 ,snake_case : List[Any]=8 ,snake_case : Dict=2048 ,snake_case : Union[str, Any]=0.75 ,snake_case : Union[str, Any]=False ,**snake_case : Optional[int] ,): super().__init__(**snake_case ) 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 =patch_size SCREAMING_SNAKE_CASE =num_channels SCREAMING_SNAKE_CASE =qkv_bias SCREAMING_SNAKE_CASE =decoder_num_attention_heads SCREAMING_SNAKE_CASE =decoder_hidden_size SCREAMING_SNAKE_CASE =decoder_num_hidden_layers SCREAMING_SNAKE_CASE =decoder_intermediate_size SCREAMING_SNAKE_CASE =mask_ratio SCREAMING_SNAKE_CASE =norm_pix_loss
334
1
def snake_case__ ( lowerCAmelCase_ = 10 ): """simple docstring""" if not isinstance(lowerCAmelCase_, lowerCAmelCase_ ) or n < 0: raise ValueError('Invalid input' ) SCREAMING_SNAKE_CASE =10**n SCREAMING_SNAKE_CASE =28433 * (pow(2, 7830457, lowerCAmelCase_ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f'{solution(10) = }')
334
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available _lowerCamelCase ={ "configuration_ernie": ["ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP", "ErnieConfig", "ErnieOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase =[ "ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST", "ErnieForCausalLM", "ErnieForMaskedLM", "ErnieForMultipleChoice", "ErnieForNextSentencePrediction", "ErnieForPreTraining", "ErnieForQuestionAnswering", "ErnieForSequenceClassification", "ErnieForTokenClassification", "ErnieModel", "ErniePreTrainedModel", ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys _lowerCamelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
334
1